简体   繁体   中英

Sequence of setTimeout in JavaScript

Can someone explain me, why if I create a function in JavaScript and add it to setTimeout , setTimeout doesn't work properly, but if I create anonymous function everything is okay? Example below:

It works:

setTimeout(function() {
    alert("foo");
}, 100);

It doesn't works:

function foo() {
    alert('foo');
}
setTimeout(foo, 100);

I checked your code, you are accessing snakeTail inside setTimeout callback. When callback function is executed after 100 ms the variable snakeTail is not available anymore. You should replace your line with

setTimeout(function(param){
    alert("Game over! Your score: "+(param-5)+" points. Wanna play again?");
    location.reload();
}, 100, snakeTail);

This way you can save the snaketail variable and pass it inside setTimeout callback.

Undersatanding setTimeout

There is no difference, how to use it, passing anonymous function to setTimeout :

setTimeout(function() {
    console.log("foo");
}, 1000);

Or passing an existing function:

function foo() {
    console.log('foo');
}
setTimeout(foo, 1000);

setTimeout is an asynchronous , so if you will use it before the regular console.log , the console.log after setTimeout function will be printed first, and then, the console.log inside setTimeout will be printed after specified delay (1 second in this case):

 setTimeout(function() { console.log("bar"); }, 1000); console.log("foo");

But if you want to log "foo" after 1 second and then to log "bar" after one second from "foo" was logged, you can add 2 second delay to the second setTimeout , like this:

 setTimeout(function() { console.log("foo"); }, 1000); function bar() { console.log('bar'); } setTimeout(bar, 2000);

Or alternatively you can wrap one setTimeout into another and give both of the 1 second delay. In this case, after 1 second will be printed "foo" , and after 2 seconds will be printed "bar" :

 setTimeout(function() { console.log("foo"); setTimeout(bar, 1000); }, 1000); function bar() { console.log('bar'); }

Hope this will give you the basic understanding of how setTimeout works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM