I know this is bad:
function sleep(millis) {
var date = new Date();
var curDate = null;
do { curDate = new Date();
} while(curDate-date < millis);
}
EDIT:
function doSomethingQuickly(pixelData) {
// loads an external image, filling the entire screen
// overlays $pixelsData over image
}
But I really do need this sort of functionality since doSomethingQuickly() returns so fast and the other doSomethingQuickly()'s cannot be allowed to run until the previous is finished. It would be disastrous to simply fire them all off and wait for results to deal with them.
doSomethingQuicky();
sleep(500);
doSomethingQuicky();
sleep(500);
doSomethingQuicky();
sleep(500);
doSomethingQuicky();
sleep(500);
doSomethingQuicky();
sleep(500);
My question is that since simulating sleep in JS is bad, how can I achieve the same using setTimeout() or another more acceptable method
NOTE: this is not in a web browser
EDIT: You can see that if it ran 5 times without the sleep, it would quickly show the final image, when what it should do is 1) show an image 2) pause for 5 seconds 3) repeatYou can see that if it ran 5 times without the sleep, it would quickly show the final images, when what it should do is 1) show an image 2) pause for 5 seconds 3) repeat
How about:
function sleep(ms,callback){
setTimeout(callback,ms);
}
//basic usage
while (someStoppingcondition){
sleep(500,doSomethingQuicky);
}
if doSomethingQuicky is always the same function, setInterval (see other answers) is sufficient. Make sure it will not run forever, use clear[Interval/Timeout] to stop the timers.
if your problem is that one function has to complete before the next one executes, this may be a way to solve it:
function firstRunner(arg1,arg2,/* ... argx*/, nextRunner){
//do things
//after things are done, run nextRunner
nextRunner();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With