Journal codefool's Journal: Sleep functionality in Javascript
The short: there is no way to pause the current thread. It must run until it ends, returning control to the browser. It is possible, however, to simulate pausing by performing a juggling act with setTimeout(), as follows:
var thread2sleepLatch = false;
function thread_2()
{...
thread2sleepLatch = false;// say thread 2 is done
}// end of function!!!
function thread_1()
{...
thread2sleepLatch = true;// say thread 2 is busy
setTimeout( "thread_2()", 10 );// fork thread 2
setTimeout( "wait_thread_2()", 10 );// juggle until thread 2 is done
}// exit!
function wait_thread_2()
{
if( thread2sleepLatch )
{
setTimeout( "wait_thread_2()", 10 );// wait some more
return;// terminate this thread!
}// get here if thread2 is done // perform post-thread2 processing ...
}
After each iteration, control is returned to the browser for 10ms, which allows the other threads to run. Note that we set thread2sleepLatch true before running the actual thread to avoid a race condition between the two threads. This is also a problem, since if thread2 never starts, then wait_thread_2 will never terminate. Hence, I reiterate my request for a sleep() function in javascript.