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.

JavaScript setTimeout()

The setTimeout() is a built-in JavaScript function that calls a function or evaluates an expression after a specified number of milliseconds. 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 the setTimeout() function does not seem to work at all.

The problem arises 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 simultaneously.

Well, that is how JavaScript works. It works on its own rules. So, for example, the setTimeout(1000) does not work like 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 functions calls to setTimeout() all run at the same time. Thus, 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 simultaneously, after the single delay of 1 second.

As 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 your JavaScript code 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 a 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 this tutorial.

Leave A Reply

Your email address will not be published.

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