1) Can someone illustrate how setTimeout works in terms of execution threads.
Consider:
function foo() { alert('foo'); }
function bar() { alert('bar'); }
setTimeout(foo,1000);
bar();
or
function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { alert('bar'); }
setTimeout(foo,1000);
bar();
or
function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { /* an execution that runs with unknown time */ }
setTimeout(foo,1000);
bar();
or
function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { /* some ajax call that reply with unknown time */ }
setTimeout(foo,1000);
bar();
or
function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { alert('foo'); setTimeout(bar,1000); }
setTimeout(foo,1000);
setTimeout(bar,1000);
2) Can someone explain how why "this" object doesn't work in setTimeout and what we can do to get around that problem?
setTimeoutiswindow, to usethisfrom the function cache it before.setInterval(foo, 100)would do the same thing better. 3) bar fully executes, and after 10 seconds foo executes. A timer pushes something to the bottom of the priority queue. 4) Again, foo will wait until bar has finished execution.