简体   繁体   中英

Javascript - Why does this code blocks?

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");

Try:

var async_func = function(x, func) {
    func(x+5);
};

setTimeout(function(){
    async_func(5, function(number) {
       console.log(number);
    });
}, 3000);

console.log("done");

(I also removed the unnecessary for (var x = 0; x < 1000000000; x++) {;} )

You should not call a function with arguments in setTimeout without making an anonymous or helper function... (If you really want to do it without setting another function check @Ian comments bellow.)

If your function didn't had any arguments you could do setTimeout(async_func, 3000); but in this case the best thing is just to call it trough an anonymous function (or declaring a calling function above calling your function with those arguments.

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:

setTimeout( async_func(5, function(number) {

executes async_func() immediately and then passes it's return result (which is not a function) to setTimeout() and that is NOT what you want. You want to pass a function reference to setTimeout() so setTimeout() can call that function later like this:

var async_func = function(x, func) {
    func(x+5);
};

setTimeout( function() {
    async_func(5, function(number) {
        for (var x = 0; x < 1000000000; x++) {;}
        console.log(number);
    });
}, 3000);

console.log("done");    

or, sometimes it's easier to understand by making your timer callback function it's own separate function with no arguments.

function async_func(x, func) {
    func(x+5);
}

function timer_func() {
    async_func(5, function(number) {
        for (var x = 0; x < 1000000000; x++) {;}
        console.log(number);
    });
}

setTimeout(timer_func, 3000);

console.log("done");    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM