Fantoni0 Fantoni0 - 5 months ago 9
Node.js Question

How to make a NodeJs function wait?

For example I have these two functions:

var count= function(){
for(i=1;i<=3;i++){
console.log(i);
}
setTimeout(function(){
for(i=1;i<=3;i++){
console.log(-i);
}
},2000);
}

var letters = function(){
var charSet = 'abcdefghijklmnopqrstuvvwxyz'
for(i=0;i<3;i++){
console.log(charSet[i]);
}
}


When I execute them in this order:

count();
letters();


I expect to get as output:

1 2 3 -1 -2 -3 a b c


But what I get is:

1 2 3 a b c -1 -2 -3


Why the function does not wait the Timeout to finish? How can I achieve the desired behaviour?

Answer

The reason that you aren't getting 1 2 3 -1 -2 -3 a b c is because your code does not stop at the setTimeout(...) call. This is because many JavaScript methods, by nature, are asynchronous. This means that they will not stop the flow of your code. That means when you call setTimeout(...), the JavaScript interpreter will make sure that the function passed into setTimeout is run in 2000ms, but does not stop and wait for it. It will continue on its normal execution flow, onto the next instruction.

If you wanted it to wait, you could put the letters() call after you print out the remaining numbers (-1, -2, -3).

    setTimeout(function(){
        for(i=1;i<=3;i++){
            console.log(-i);
         }
         letters();
    },2000);