What’s wrong with my script? - setTimeOut

Asked

Viewed 201 times

1

Hello! The script below takes an id image assinatura and applies an effect on it when my scroll is at a certain site height.

$(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            $("#assinatura").addClass("animated jello");
        }
    });

However, I would like when the scroll reaches 400 or higher, the program to wait 2 seconds to apply the effect I wanted. (2 seconds to test).

So I tried to do the way below, but that resulted in the same thing as the previous one, IE, the program is only running as if I did not hear the setTimeOut:

$(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            window.setTimeout($("#assinatura").addClass("animated jello"), 5000);
        }
    });

3 answers

3


On the console (F12) you can see that the problem is:

Uncaught SyntaxError: Unexpected identifier

The setTimeout expects the first parameter to be a function or a string of code, see here:

setTimeout(func[, delay, param1, param2, ...]);
setTimeout(code[, delay]);

This way you have the following solutions:

1. Create an anonymous function:

setTimeout(function() {
    $("#assinatura").addClass("animated jello")
}, 5000);

2. Creating a function and calling it:

function animate(){
   $("#assinatura").addClass("animated jello")
}

setTimeout(animate, 5000);

If function requires any argument you can enter the value after the delay.

3. Making a string for an Eval():

setTimeout('$("#assinatura").addClass("animated jello")', 5000);

That one solution is not recommended and local variables cannot be accessed.

  • I don’t like the idea of you saying "how" to fix but not saying "what’s wrong" and why. The OP will now decorate that have to put the "Function" around your call, and find that it is magic.

  • I improved it and added the possibility without the need for function.

2

Try to replace this section:

if (scroll >= 400) {
    window.setTimeout($("#assinatura").addClass("animated jello"), 5000);
}

for

if (scroll >= 400) {
    window.setTimeout(function() {
        $("#assinatura").addClass("animated jello")
    }, 5000);
}

It occurs that the parameter of the setTimeout receives a function, and with your code, you are calling the function addClass immediately and passing her return.

0

You have to pass a function and to setInterval or setTimeout. Ex:

setInterval(function(){ /*Minha declaração*/ },1000) ou setInterval(() => {/* Minha declaração */},1000)
  • The setInterval and setTimeout are completely different functions, the setInterval will perform the function every 1 second and not just after 1 second. : S

Browser other questions tagged

You are not signed in. Login or sign up in order to post.