I Don’t get why this code blocks. I use nodejs async functions, but now I’m trying to figure out what’s the essence of non-blocking programming, and how can I implement those.
This is the way I thought it would be, but Its still blocking.
var async_func = function(x, func) {
func(x+5);
};
setTimeout( async_func(5, function(number) {
for (var x = 0; x < 1000000000; x++) {;}
console.log(number);
}), 3000);
console.log("done");
This is a common mistake when using
setTimeout()and when passing function references where you want to call a function with arguments. This line of code:executes
async_func()immediately and then passes it’s return result (which is not a function) tosetTimeout()and that is NOT what you want. You want to pass a function reference tosetTimeout()sosetTimeout()can call that function later like this:or, sometimes it’s easier to understand by making your timer callback function it’s own separate function with no arguments.