elszczepano elszczepano - 3 years ago 240
Javascript Question

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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download