Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout function unexpected behavior

I have the following code to append iframes from an elements array in batch sizes of 10 with a time interval of 10 seconds per batch. Batches is an array which has a JSON object with start and end indexes for each batch. Append function appends the iframe with code to the DOM.

Current behavior: JS waits for 10 seconds and calls the append function together while appending all the iframes in one go without waiting for 10 seconds each batch.

Expected behavior: JS waits for 10 seconds before appending each batch or each append function call.

batches.forEach(function (x) {
    setTimeout(function () {
        append(x, elements);
        console.log('appending'+x);
    }, 10000);
});

Any idea why this could be happening?

like image 256
Arihant Avatar asked Sep 09 '26 22:09

Arihant


1 Answers

setTimeout does not pause execution so your code is the equivalent of

setTimeout(..., 10000)
setTimeout(..., 10000)
setTimeout(..., 10000)
// etc

where each timeout call is set to execute at roughly the same time, 10 seconds from now.

You're going to have to increase the timeout in each iteration. Something like this...

batches.forEach((x, i) => { // where "i" is the current, zero-based index
  setTimeout(() => {
    // etc
  }, 10000 * (i + 1))
})
like image 82
Phil Avatar answered Sep 12 '26 13:09

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!