Follow Slashdot blog updates by subscribing to our blog RSS feed

 



Forgot your password?
typodupeerror
×
Programming

Journal codefool's Journal: Sleep functionality in Javascript

There really is a deep need for a sleep() function in javascript. That is, a function that suspends the current thread so that some other thread(s) can complete processing. Currently, however, Javascript does not have a sleep function, but one can be simulated using window.setTimeout, but its not as simple as an embedded sleep() call would be.

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.

He has not acquired a fortune; the fortune has acquired him. -- Bion

Working...