DEV Community

Avnish
Avnish

Posted on

How to Wait 1 Second in JavaScript

How to Wait 1 Second in JavaScript

In JavaScript, delaying the execution of code for a specified amount of time can be achieved using a variety of methods. This is often required in scenarios such as rate-limiting API calls, creating animations, or introducing delays in logic. Here, we explore several ways to wait for 1 second in JavaScript, complete with code examples and explanations.


Using Promises and setTimeout

The setTimeout() function allows you to execute a callback after a specified time (in milliseconds). By combining setTimeout() with Promises, you can create a reusable delay function:

Code Example

function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

delay(1000).then(() => console.log('Ran after 1 second'));
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. delay(time) Function:

    • Wraps a Promise.
    • The resolve function is called after time milliseconds using setTimeout().
  2. delay(1000) Call:

    • Creates a delay of 1000 milliseconds (1 second).
    • The .then() method executes the provided callback (console.log('Ran after 1 second')) after the delay.

Using async/await

async/await syntax makes handling asynchronous operations more readable. Here's how you can use it with the delay function.

Code Example

function delay(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

async function test() {
  console.log('Start timer');
  await delay(1000);
  console.log('After 1 second');
}

test();
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. async function test():

    • Declares an asynchronous function where await can be used.
  2. await delay(1000):

    • Pauses execution of the function for 1 second until the Promise resolves.
  3. Output:

    • "Start timer" is logged immediately.
    • "After 1 second" is logged after a 1-second delay.

Inlining the Delay Logic

You can skip creating a separate delay function by inlining the Promise inside your async function.

Code Example

async function test() {
  console.log('Start timer');
  await new Promise(resolve => setTimeout(resolve, 1000));
  console.log('After 1 second');
}

test();
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Inline Promise:

    • The delay logic is directly included inside the await statement.
  2. Behavior:

    • Functions the same as the previous example without requiring an external delay function.

Using Traditional Callbacks

Before Promises were widely adopted, setTimeout() was often used with callback functions.

Code Example

function delayCallback(callback, time) {
  setTimeout(callback, time);
}

delayCallback(() => console.log('Ran after 1 second'), 1000);
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Callback-Driven Approach:

    • Passes a callback function to delayCallback().
    • setTimeout() invokes the callback after 1 second.
  2. Limitations:

    • This approach can lead to "callback hell" if delays need to be chained.

Comparing the Approaches

Method Advantages Disadvantages
Promises + setTimeout Clean and reusable function Requires .then() chaining
async/await Synchronous-like syntax for async ops Requires async functions
Inline Promise Eliminates the need for extra functions May reduce readability
Callback Simple for one-time delays Less readable for complex flows

Conclusion

To introduce a 1-second delay in JavaScript, the most modern and maintainable approaches involve Promises and async/await. For simple use cases, an inline Promise suffices, but reusable functions like delay() improve code modularity and readability.

Top comments (0)