What's wrong with my script? - setTimeOut

1

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

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

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

However, I would like that when the scroll reaches 400 or more in height, the program waited 2 seconds to apply the effect I wanted. (2 seconds for testing).

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

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

        if (scroll >= 400) {
            window.setTimeout($("#assinatura").addClass("animated jello"), 5000);
        }
    });
    
asked by anonymous 13.01.2017 / 02:24

3 answers

3

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

Uncaught SyntaxError: Unexpected identifier

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

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

That way you have the following solutions:

1. Create an anonymous function:

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

2. Create a function and call it:

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

setTimeout(animate, 5000);
  

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

3. Make a string for an eval ():

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

This solution is not recommended and local variables can not be accessed.

    
13.01.2017 / 02:31
2

Try to replace this section:

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

by

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

The setTimeout parameter is given a function, and with its code, you are calling the function addClass immediately and passing it back.

    
13.01.2017 / 02:31
0

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

setInterval(function(){ /*Minha declaração*/ },1000) ou setInterval(() => {/* Minha declaração */},1000)
    
13.01.2017 / 16:57