Wednesday, November 21, 2007

Javascript : tricky thing for setTimeout

I have this:

function callme() {
alert('can you hear me?');
}

What's the difference among these calls?
1) setTimeout(alert('can you hear me?'), 1000);
2) setTimeout(callme(), 1000);
3) setTimeout(function () { callme(); }, 1000);

1) and 2) are the same, callme() will be executed when setTimeout processing its parameter.
3) will be called after 1000ms, likely asynchronized.

---
Roger says:
"the arguments are evaluated when setTimeout is called, so is that init function, what might work is just passing callme which is an object.

the latter (case 2) preserves the variables so to speak... scope, context"

No comments: