A
A
Alexey Ivanov2015-01-29 00:28:04
Node.js
Alexey Ivanov, 2015-01-29 00:28:04

How to execute synchronously loop in nodeJS?

Hello, need to iterate in order, how to achieve this in nodeJS?
There is a code:

for(var i = 1; i <= 10; i++) {
  setTimeout(function(){
    console.log('Индекс: ' + i);
  }, 5000 / i);
}

The output is: Index: 11, Index: 11, Index: 11, Index: 11, Index: 11...
How to get: Index: 10, Index: 9, Index: 8... ?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Y
Yuri Shikanov, 2015-01-29
@Kandiar

Something like this :)

for(var i = 0; i <= 10; i++) {
    console.log('Индекс: ' + i);
}

or if necessary asynchronously, then we use closures:
for(var i = 0; i <= 10; i++) {
  (function(i) {
  setTimeout(function(){
    console.log('Индекс: ' + i);
  }, 5000 / i);
  })(i);
}

I
index0h, 2015-01-29
@index0h

var func = function (i) {
    return function () {
        console.log('Индекс: ' + i);
    };
};
for(var i = 0; i <= 10; i++) {
  setTimeout(func(i), 5000 / i);
}

Only i != 0, because dividing by 0 will
It doesn’t roll, your i increases, and the delay decreases, it will be in the reverse order. 10 -> 1

S
Sergey Nalomenko, 2015-01-29
@nalomenko

Read up on variable scoping and, if you like, closures in Javascript. This will completely help you understand where critical errors are made in your code.

V
vmb, 2015-01-29
@vmb

What if you use "use strict"; and let instead of var? It works on io.js, but I don’t know how it is in Node with your version with let support. True, the index order is reversed: 0, 10, 9... And this is logical, judging by the interval set in the timer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question