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

doesn't work properly, but if I create anonymous function everything is okay? Example below:

It works:

setTimeout(function() {
}, 100);

It doesn't works:

function 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

    alert("Game over! Your score: "+(param-5)+" points. Wanna play again?");
}, 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