Skip to main content

Archive

Show more

How To Wait In JavaScript

How To Wait In JavaScript

Waiting or delaying code execution in JavaScript is essential for handling asynchronous operations, animations, and timed events. JavaScript provides several methods for introducing delays or waiting periods in code. This article explores different ways to wait in JavaScript and provides examples for each approach.


Using setTimeout()

The setTimeout() function allows you to execute a piece of code after a specified delay. The delay is defined in milliseconds.


// Using setTimeout to wait
console.log('Start');

setTimeout(() => {
  console.log('This message is shown after a 2-second delay');
}, 2000); // Delay of 2000 milliseconds (2 seconds)

console.log('End');

In this example:

  • setTimeout() is used to delay the execution of a function by 2000 milliseconds.
  • The message "This message is shown after a 2-second delay" appears after a 2-second pause.

Using setInterval()

The setInterval() function repeatedly executes a piece of code at specified intervals. The delay is defined in milliseconds, and the code runs continuously until clearInterval() is called.


// Using setInterval to wait repeatedly
let count = 0;
const intervalId = setInterval(() => {
  count++;
  console.log(`Interval count: ${count}`);
  
  if (count === 5) {
    clearInterval(intervalId); // Stop the interval after 5 executions
  }
}, 1000); // Interval of 1000 milliseconds (1 second)

In this example:

  • setInterval() is used to execute the code every 1000 milliseconds.
  • The interval is cleared after 5 executions using clearInterval().

Using Promises with async/await

Modern JavaScript allows for asynchronous operations using Promises and async/await syntax. You can create a delay by wrapping setTimeout() in a Promise and then use await to wait for the Promise to resolve.


// Using Promises and async/await to wait
function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function execute() {
  console.log('Start');
  await wait(2000); // Wait for 2 seconds
  console.log('This message is shown after a 2-second delay');
  console.log('End');
}

execute();

In this example:

  • The wait() function returns a Promise that resolves after a specified delay.
  • The execute() function uses await to pause execution until the Promise resolves.

Using requestAnimationFrame()

The requestAnimationFrame() function is used for creating smooth animations by calling a function before the next repaint. It does not provide a delay but is useful for animating elements in sync with the browser's refresh rate.


// Using requestAnimationFrame to wait for the next repaint
let startTime = null;

function animate(timestamp) {
  if (!startTime) startTime = timestamp;
  const progress = timestamp - startTime;
  
  if (progress < 2000) { // 2 seconds delay
    requestAnimationFrame(animate);
  } else {
    console.log('Animation completed after 2 seconds');
  }
}

requestAnimationFrame(animate);

In this example:

  • requestAnimationFrame() is used to create an animation that waits until the next repaint.
  • The function continues to be called until 2 seconds have passed.

Conclusion

Waiting or introducing delays in JavaScript can be achieved using various methods such as setTimeout(), setInterval(), Promises with async/await, and requestAnimationFrame(). Each method has its specific use case, and selecting the appropriate one depends on the requirements of your application.

Comments