Unable to set timeout in Node.js loop

Here I tried to set a timeout for each iteration, but I could not do it because the nature of nodejs. Is there any way to do this?

Thanks in advance

for (var i = 1; i <= 1000; i++) {
    setTimeout(function () { console.log('something') }, 3000); 
}
Run codeHide result
+4
source share
3 answers

It works, but it sets all the timeouts at the same time.

If you want to schedule them at 3-second intervals, use:

for (var i = 1; i <= 1000; i++) {
    setTimeout(function () { console.log('something') }, i * 3000);
}

If you want to use itimeouts inside your callbacks, use letinstead varas follows:

for (let i = 1; i <= 1000; i++) {
    setTimeout(function () { console.log('something', i) }, i * 3000);
}

As you can see with help var, it will print 1001 for each line:

for (var i = 1; i <= 1000; i++) {
    setTimeout(function () { console.log('something', i) }, i * 3000);
}

, , :

for (let i = 1; i <= 1000; i++) {
    setTimeout(() => console.log('something', i), i * 3000);
}

- - - , 1000 , :

(() => {
    let i = 0;
    setInterval(() => {
        i++;
        console.log('something', i);
    }, 3000);
})();

, i . - :

(() => {
    let i = 0;
    let f = () => {
        i++;
        console.log('something', i);
        setTimeout(f, 3000);
    };
    setTimeout(f, 3000);
})();

, , , .

, .

, setInterval, , . , setTimeout , , , . , .

+5

for (var i = 1; i <= 10; i++) {
     wait('something', i, 10);
}

function wait(msg, i, length){
    setTimeout(function () 
    { 
    console.log(msg) ;
    }, (i * 3000));
}
Hide result

- . , 3 , 1 , .

+2

, setInterval.

let runMeEveryThreeSeconds = function() {
  console.log('hello!')
}
let threeSecondTimer = setInterval(runMeEveryThreeSeconds, 3000)

, "!" . , :

clearInterval(threeSecondTimer)
0

Source: https://habr.com/ru/post/1672355/


All Articles