• How To Slow Down A for-loop in JavaScript
  • Originally written by Louis Petrik
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Hoarfroster
  • Proofreader: Usualminds, Samyu2000

How do I slow down loops in JavaScript

The For loop is essential in JavaScript. Using the For loop, we can write programs that relate to lists. But there’s a problem — the For loop is executed as fast as possible. And of course if we just use it to go through the array that’s absolutely fine.

However, if we execute requests in a loop, there may be some problems (such as high request speeds causing the server to block IP and other undesirable situations). It would be great if we could execute a loop every once in a while (For example, execute a loop every second), so that the For loop would execute slower.

In the following, we will embark on a journey of discovery

First: ineffective methods

If you’re looking for a direct solution to the problem, skip ahead. If you want to learn more about JavaScript, please don’t hesitate

I’d like to start by explaining why common solutions don’t work.

Thanks to JavaScript’s setTimeout method, we can execute code after a certain amount of time. Yi? We just add setTimeout to the body of the For loop and the loop will slow down:

for (let i = 0; i < 100; i++) {
    setTimeout(() = > {
        console.log(i);
    }, 1000);
}
Copy the code

But when we run the code above, the following happens:

  • At first there was a delay, then all the logs were printed on the console at the same time.

That’s not what we want at all

The reason for this is that we have fallen into a trap. It doesn’t seem like the For loop has a timeout set For each element either (in fact, the program does).

We just forgot how JavaScript executes code. The loop creates all timeouts at once, not sequentially. This is very fast, and therefore all timeouts have nearly the same start time.

Once the set time is up, all tasks are executed immediately — and a log is printed.

Even if we were to rewrite the code as follows, we would still see the same effect.

for (let i = 0; i < 100; i++) {
    setTimeout(() = >{},1000);
    console.log(i);
}
Copy the code

If we take this idea as a starting point, we can actually achieve our goal in some other programming languages — at least in some other programming languages — where loops create timeouts and only execute when those tasks are completed. However, in JavaScript, the program doesn’t stop, it just continues to create a timeout. The code just keeps executing and doesn’t stay there. Thus, JavaScript can be thought of as creating two threads running in parallel to handle both the For loop and the timeout created by the For loop.

How do I properly slow down the For loop

Obviously, if we only use setTimeout, we will never achieve our expectations, so what should we do?

The solution is as simple as a simple Promise statement.

const sleep = (time) = > {
    return new Promise((resolve) = > {
        return setTimeout(function () {
            resolve()
        }, time)
    })
}
Copy the code

We call the Promise through the function, which gets the time (in milliseconds) when setTimeout should be set. After a certain amount of time, all timeouts execute resolve. This means that we have carried out the Promise. We can simplify the code shown above:

const sleep = (time) = > {
    return new Promise(resolve= > setTimeout(resolve, time))
}
Copy the code

Use Promise to implement what we need. Now let’s add it to the For loop:

const sleep = (time) = > {
    return new Promise((resolve) = > setTimeout(resolve, time))
}

const doSomething = async() = > {for (let i = 0; i < 100; i++) {
        await sleep(1000)
        console.log(i)
    }
}

doSomething()
Copy the code

The program prints logs every second. So, to output all the numbers for the loop, we need to wait 100 seconds. We have now successfully slowed down the For loop!

Thanks for reading!

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.