Can jQuery be used as a sleep() or wait() function? Suspending the execution of the statements after the wait. I tried $().delay(5000) but there was no 5 second wait. Is delay() only used in effects?
I am not looking for solutions which involve setTimeout delayed execution of another function or a CPU hogging solution. I want a sleep() function which can be reused in different scripts.
Addition:
I didn’t mean to suggest a solution which doesn’t use setTimeout at all. I have seen solutions which required to move all code after where the delay is needed into its own function so that setTimeout can call it. I don’t want that. Either a self contained wrapper function for using setTimeout or use jQuery delay() in a dummy non visual effect just for the purpose of simulating a sleep function.
Javascript (and by extension, jQuery) doesn’t have a real “sleep” function. You can more or less abuse setTimeout & setInterval (and their derivatives, like delay) to simulate sleep, but you’re usually better off just adapting to the setInterval/Timeout way of doing things… figure out what you want done, seal it off in a function, pass it as an argument to one of those two.
Edit:
Okay, I see your edit. You really want a conventional sleep function. What follows is absolutely an abuse and not at all what I’d recommend. But if I had to build one to save my life, here’s how I’d do it: test how long a high number of loop cycles takes, do a statistically significant number of these tests, average the results, and use that information to define a function that roughly translates a given number of milliseconds into a number of loop cycles, which it then runs through.
In JavaScript:
I wouldn’t trust my life, health, or even $20 to the accuracy of the timing, though. If you need any degree of precision finer than half a second, the right way to do this in JavaScript is to trust the facilities built into whatever environment you’re using… and in the browser, that’s setInterval and setTimeout.
Edit #2:
I see the recommendation for Ben Alman’s doTimeout plugin in one of the comments. After looking it over, it’s worth noting that it is a better idea than the abomination I have produced above in just about every way. It isn’t quite the comfortable
sleep-y syntax we’re often used to, and you still have to think about your code in functions in some marginal way, but at least you can still keep the sequential feel. If you can’t bring yourself to use setTimeout/Interval directly, use doTimeout or something like it.