Skip to main content
How To Create Wait Function in Javascript

How To Create Wait Function in Javascript

This javascript tutorial help to create wait() a function, The js does not have an inbuilt wait or sleep function to halt execution for a while.

The following JavaScript functions can be used to time events in your project.

  • setTimeout()
  • clearInterval()
  • setInterval()

What is sleep() function

The sleep function 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 JavaScript function that executes a function or evaluates an expression after a certain number of milliseconds. Unfortunately, depending on how you use it, standalone setTimeout() does not work as expected. You may have previously tested it and discovered that the setTimeout() function does not appear to work at all throughout the JavaScript loop.

The sample example:

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

We want to log the value i every 2 seconds until the for loop condition is false, but the execution will pause for 2 seconds and then print the 5 values at a time.

Output:

#1
#2
#3
#4
#5

Create Wait Function

We’ll create our custom method for wait execution for a while. we’ll use Promises, async/await, and setTimeout() methods to write the wait function that will work as you would expect it.

Let’s create a new file called app.js and write the following code inside that file:

const list = [1, 2, 3, 4]
const wait = async (sec) => {
  for (const item of list) {
    await new Promise(r => setTimeout(r, sec));
    console.log('wait', item );
  }
}

wait(2000);

Output:

wait 1
wait 2
wait 3
wait 4

Leave a Reply

Your email address will not be published. Required fields are marked *