AppDividend
Latest Code Tutorials

JavaScript Wait: How to Make Function Wait in JavaScript

0

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.

But when you run the code, that won’t happen. Instead, the execution will pause for 1 second and then print the 5 values at a time.

Well, that’s not what is supposed to happen. We need to log the values every 1 second and not just wait for 1 second and log all the values at the same time.

Well, that is how JavaScript works. It works on its own rules. The setTimeout(1000) does not work like it will be waiting for 1 second between your calls to the console.log() function.

See the output.

 node app
#1
#2
#3
#4
#5

This results in all five console log messages being displayed together, after the single delay of  1 second, instead of the desired effect of the delay of 1 second between each repeated call.

The reason behind this is that setTimeout() function is executed as synchronous code and the multiple function calls to setTimeout() all run at the same time. Each call to setTimeout() creates an asynchronous code that will execute later, after a given delay. Since each delay in the code snippet was the same (1000ms or 1 second), all the queued code runs at the same time, after the single delay of 1 second.

As we have discussed, the setTimeout() is not a sleep() function; instead, it just queues asynchronous code for later execution.

But fortunately, it is possible to use setTimeout() to create your own sleep() function in JavaScript.

JavaScript wait()

To make JavaScript wait, use the combination of Promises, async/await, and setTimeout() function through which you can write the wait() function that will work as you would expect it should.

However, you can only call this custom wait() function from within async functions, and you need to use the await keyword with it.

wait() example in JavaScript

Create a new file called app.js and write the following code inside that file.

// app.js

const list = [1, 2, 3, 4]
const task = async () => {
  for (const item of list) {
    await new Promise(r => setTimeout(r, 1000));
    console.log('Yello, D\'oh');
  }
}

task();

Output

node app
Yello, D'oh
Yello, D'oh
Yello, D'oh
Yello, D'oh

Here, we use this just one line of code that will do the wait for us.

await new Promise(r => setTimeout(r, 1000));

This code works exactly as you might have expected because await causes the synchronous execution of a code to pause until the Promise is resolved.

Conclusion

JavaScript may not have the sleep() or wait() function, but it is easy enough to create a function or write a single line of code using an inbuilt setTimeout() function as long as you are very careful about the code and how you use it.

By itself, the setTimeout() function does not work as the sleep() method, but you can create a custom JavaScript sleep() or wait() function using async and await.

That is it for the Javascript wait example.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.