setTimeout drives me crazy. How can I implement "sleep" without going insane?
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 patt…
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);