Javascript sleep()21st March 2008, 442 views The abscence of a sleep() function in Javascript is, im my opinion, a big oversight. Here's an emulation. It's usually off by a few milliseconds, though I suppose it depends one how fast your PC is. One drawback is that it blocks, ie doesn't allow any other UI input. Or at least it seems to. Depending on how you want to use it though and what for, this may not be an issue. Top 10 referrering pages
Link to meIf you use any of the code on this site (and if you don't I guess) or it makes your life easier, I'd appreciate a link - http://www.phpguru.org. Thanks!
Author: Richard Heyes
Posted: 23rd March 2008 11:29 isao:
Quote> you're wrong, in a way. javascript has a > setTimeout which is similar, and maybe better. Yes I know of setTimeout() and yes it's similar, but by no means better, and in some circumstances, totally unusable.
Author: Michael Gauthier
Posted: 24th March 2008 23:35 The problem with using a while(true) loop is that you will cause 100% CPU usage during execution. setTimeout() is much better for almost anything which you'd want to use sleep() for.
QuoteSleep is generally used to rate-limit execution of a program so as not to hog the CPU or to delay execution of some task. A while(true) loop is worse than setTimeout() for both of these tasks.
Author: Richard Heyes
Posted: 25th March 2008 11:25 Michael Gauthier:
Quote> The problem with using a while(true) loop is > that you will cause 100% CPU usage during > execution. setTimeout() is much better for > almost anything which you'd want to use sleep() > for. No, it's not. Were this function not to block, it would be ideal. > Sleep is generally used to rate-limit execution > of a program so as not to hog the CPU or to > delay execution of some task. That's one use for sure, but it's not exactly a general use. > A while(true) > loop is worse than setTimeout() for both of > these tasks. It's by no means ideal, but given the extra control flow you would need to put in place if you were to use setTimeout(), or code separation, it's not so bad in some cases. |

Comments
Posted: 23rd March 2008 07:48
setTimeout(funcname, 1000);
function funcname()
{
alert('done');
}
i don't reccommend while(true) loops for delays...