Posts Tagged Thread
Equivalent of a Thread.sleep in javascript
Posted by Jocelyn in Javascript, Web Development on November 24, 2011
Lately, a colleague of mine asked me if it was possible to wait for an event in javascript. He had to work with a third party program, and he had to intercept something in order to properly display information. But there were no events or anything on which to hook.
The solution we came with was to do some kind of loop, which waits until something becomes available, and expires if a timeout is met.
I used the setTimeout method of javascript, within a recursive method and a count in order to watch for a timeout.
Here’s the code I came up with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | var MAX_TRIES = 10; var NEXT_TRY_TIMER = 500; function tryUntilSuccess( tryCount ) { if( !tryCount ) { tryCount = 0; } else if( tryCount == MAX_TRIES ) { alert( "TIMEOUT" ); return; } alert( "Try: " + tryCount ); try { // This is only to show what happens if an exception is thrown. throw "What I'm waiting for didn't happen, so I throw an exception."; } catch( e ) { setTimeout( function() { tryUntilSuccess( ++tryCount ); }, NEXT_TRY_TIMER); } } tryUntilSuccess(); |
Alerts are there only to illustrate the behavior of the code, and should be removed, and the exception should be thrown in the situation where you don’t have what you need.