JavaScript does not provide any native functions like wait(). When it comes to JavaScript Timing Events, there are the following functions that you can use in your project.

  1. setTimeout()
  2. clearInterval()
  3. setInterval()

Many programming languages have the sleep function that will wait for the program’s execution for a given number of seconds. But JavaScript does not have that native function.

Understanding JavaScript setTimeout()

To make JavaScript wait, use setTimeout() function with JavaScript promise. But, Unfortunately, standalone setTimeout() does not work quite as you might expect, based on how you use it. You may have already tried it at some point in the JavaScript loop and seen that setTimeout() function does not seem to work at all.

The problem rises from misunderstanding setTimeout() as a sleep() function of other languages when it works according to its own set of rules.

Let’s see the following code.

// app.js

for (let i = 1; i <= 5; i++) {
  setTimeout(() => console.log(`#${i}`), 1000);

In the above code, what we are trying to achieve is that we want to log the value i every 1 second until the for loop condition will be false.

#javascript #programming

How to Make Function Wait in JavaScript
2.20 GEEK