0

I have a problem with code below:

var async = require("async");

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

function hello(no){
    console.log(no);
    async.forEach(no,function print_list(x, callback){
        console.log("I am task number : ", x);
        var sleep_time = Math.floor((Math.random()*10)+1);
        console.log(sleep_time);
        sleep(sleep_time*1000);
    },function(err){if (err){console.log(err);}});
}

list = [];
for (var a = 1000; a > 0;a--){
    list.push(a);
};
hello(list);

In my mind I'm expecting that each this code will not block each other, but I found out that is still treated as synchronous code.

Where did I do it wrong?

1 Answer 1

5

Node.js is single threaded and your sleep function is taking over the CPU.

Try using setTimeout instead to have a more realistic example on how this works.

function hello(no){
    console.log(no);
    async.forEach(no,function print_list(x, callback){
        console.log("I am task number : ", x);
        var sleep_time = Math.floor((Math.random()*10)+1);
        console.log(sleep_time);
        // use setTimeout
        setTimeout( function() {}, sleep_time*1000);
    },function(err){if (err){console.log(err);}});
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.