JavaScript runs in a single thread, which is why a lot of things, including XHR, work with callbacks. But sometimes, sometimes you need to escape the thread [1] and run you code in a new one. One example is event based code, where your stuff should not run while the event is still being propagated. The easiest way to accomplish this is by using setTimeout():
setTimeout(myCode, 0);
Since JavaScript is single-threaded, and the timeout 0 milliseconds, the timer will fire when there is no JavaScript being executed. In theory it’s still possible for other threads to be started, blocking the timer, but this shouldn’t lead to any practical problems.
Happy coding!
[1]: For sake of argument. Technically it’s all the same thread, and execution would depend on queues and callstacks, but I find it easier to think of this as in different threads.

Wouldn’t this be a litle more accurate?
Oops! Thanks Matthias
good point. i came across this problem recently when i noticed Safari doesn’t like to execute “trigger mouse event” function from within an event handler. IE and FF seemed to be ok with it!
probably a bad idea to assume an implementation of JS is single threaded, the key concept is that the setTimeout call is asynchronous…
Great tip, thanks…. everyday there’s something new to learn when it comes to Js/Ajax..
As you said, javascript is single threaded but there are ways around this that can help you create calls that run in the background, giving you the illusion of a threaded system. I suppose this is the other side of the coin from what you are suggesting above but certainly it’s an interesting concept. Have a look here : http://www.hwhappy.co.uk/2006/11/07/concurrent-xml-queries-with-ajax/
Not quite. With asynchronous XHR, the actual request is made without blocking the JavaScript thread (as with synchronous XHR). Then, when the request finishes, a JavaScript method is invoked, which is single-threaded. Due to browser limitations there most likely won’t be more than two XHR requests to the same server at the same time, so it’s not even truly concurrent on the browser side of things.
umm, setTimeout(“fuction()”,0);
that would just call the fuction fucntion() every 0 milliseconds right?
how would that implement a thread, especially if you need to move an object over a cetain period of time?
would you just put another function inside the function you’re calling every 0 milliseconds?
for example:
var time = 0;
fcn1();
function fcn1() {
if(time < 1) { fcn2(); time++; }
setTimeout(“fcn1()”,0);
}
is this a good example?
even in this example, fcn2 is just goin to happen every 400 sec. so I dont see how setting the time recurrencey to 0 helps any.
It’s not really threading, more scheduling a function to be executed in a new call stack. You’re looking for
setIntervalwhich is unrelated to this discussion.