Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need JavaScript sleep() replacement

Tags:

javascript

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

like image 794
Tabby Laredo Avatar asked Mar 25 '26 00:03

Tabby Laredo


1 Answers

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();
}
like image 139
KooiInc Avatar answered Mar 26 '26 15:03

KooiInc