Here's one very simple example:
for (var i = 0; i < 10; i++) {
window.setTimeout(function() {
console.log(i);
}, 2000);
}
You might expect these console.log()
calls to show you 0, 1, 2
etc., as in this snippet:
for (var i = 0; i < 10; i++) {
console.log(i);
}
But in fact only 10
s will be printed! The reason that functions passed into setTimeout
function (as its 'callback' argument) will be invoked after for
loop is completed - i.e., after i
value is set to 10.
Yet you should understood one thing: all JavaScript in a browser executes on a single thread; asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution queue. Here's a brilliant article written by John Resig on this topic.