Skip to content

Instantly share code, notes, and snippets.

@addisaden
Created December 1, 2012 13:42
Show Gist options
  • Select an option

  • Save addisaden/4182302 to your computer and use it in GitHub Desktop.

Select an option

Save addisaden/4182302 to your computer and use it in GitHub Desktop.
Why is this code blocking?
var worker_clb = function(name, clb) {
var d = new Date();
for(var i = 0; i < 100000000; i++) {
i+i;
}
clb(name + "_clb returns after " + ((new Date()) - d) + " ms.");
}
var a_lot_to_do = function(name, clb) {
worker_clb(name, clb);
clb(name + " is fired");
}
a_lot_to_do("w1", console.log);
a_lot_to_do("w2", console.log);
a_lot_to_do("w3", console.log);
a_lot_to_do("w4", console.log);
@addisaden
Copy link
Author

Output:

w1_clb returns after 221 ms.
w1 is fired
w2_clb returns after 223 ms.
w2 is fired
w3_clb returns after 221 ms.
w3 is fired
w4_clb returns after 221 ms.
w4 is fired

shouldn't it be like this?

w1 is fired
w2 is fired
w3 is fired
w4 is fired
w1_clb returns after 221 ms.
w2_clb returns after 223 ms.
w3_clb returns after 221 ms.
w4_clb returns after 221 ms.

@sameei
Copy link

sameei commented Nov 30, 2013

No; Output is true! You're only one thread to run your code! so NodeJs runs "worker_clb" and next runs " clb(name + " is fired");". your code isn't async || non-blocking !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment