Re:Offer HN: I'll answer your javascript questions
by heyrhett on Saturday December 18, 2010 @12:50AM
(#2018990)
setTimeout drives me crazy. How can I implement "sleep" without going insane?
[ Parent
| on HN ]
Re:Offer HN: I'll answer your javascript questions
by geuis on Saturday December 18, 2010 @01:23AM
(#2019038)
So you should never think of "sleep" in javascript. Since the language is single-threaded, really if you pause the script you're pausing the entire environment (whether its in the browser or on the server in something like Node.js).
But, to answer your question:
// some code runs here
var continue = function(data){ //more code runs in here after sleep }
setTimeout(function(){ continue(data); },2000);
A different pattern:
var obj = { sleep: function(fn, time){ setTimeout(fn, time ); }, func1: function(data){ console.log('Continuing'); }, init: function(data){
console.log('Starting');
obj.sleep(obj.func1, 2000);
}
}
obj.init()
Re:Offer HN: I'll answer your javascript questions
by psykotic on Saturday December 18, 2010 @01:53AM
(#2019080)
IMO, a better pattern is to use lexical closures in continuation-passing style to share state:
function sleep(time, continuation) {
setTimeout(continuation, time);
}
function start_process(x) {
var y = foo(x);
sleep(1000, function() {
var z = bar(x, y);
sleep(2000, function() {
baz(x, y, z);
});});
}
start_process(42);
Re:Offer HN: I'll answer your javascript questions
by geuis on Saturday December 18, 2010 @01:35PM
(#2019938)
Except that you basically wrote the same thing as my second example, except your functions aren't namespaced and are polluting globals.
Re:Offer HN: I'll answer your javascript questions
by johnswamps on Saturday December 18, 2010 @01:12AM
(#2019027)
Your problem is not with setTimeout, you need to learn how to write evented code because that is how javascript works and you're going to encounter this problem in different contexts. Passing in a closure to setTimeout usually suffices though, it's just slightly uglier than a normal "sleep" call.
If you really, really wanted to you could create a busy wait sleep function, but it's an awful idea and you should never do it.