0
0
JavascriptHow-ToBeginner · 3 min read

How to Wait for 1 Second in JavaScript: Simple Guide

To wait for 1 second in JavaScript, use setTimeout inside a Promise and combine it with async/await. This pauses the code execution for 1000 milliseconds before continuing.
📐

Syntax

Use setTimeout wrapped in a Promise to create a delay function. Then use await to pause execution until the delay finishes.

  • delay(ms): A function that returns a promise resolving after ms milliseconds.
  • await delay(1000): Pauses the async function for 1000 milliseconds (1 second).
javascript
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function waitOneSecond() {
  console.log('Wait starts');
  await delay(1000); // waits 1 second
  console.log('Wait ends after 1 second');
}
💻

Example

This example shows how to wait for 1 second inside an async function using await and setTimeout. The console logs before and after the wait demonstrate the pause.

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

async function waitOneSecond() {
  console.log('Wait starts');
  await delay(1000); // waits 1 second
  console.log('Wait ends after 1 second');
}

waitOneSecond();
Output
Wait starts Wait ends after 1 second
⚠️

Common Pitfalls

Many beginners try to use setTimeout alone expecting it to pause code execution, but it only schedules a callback and does not block the code.

Wrong way:

console.log('Start');
setTimeout(() => console.log('After 1 second'), 1000);
console.log('End');

This prints 'Start', then 'End' immediately, and 'After 1 second' later.

Right way is to use async/await with a promise as shown in the example.

javascript
console.log('Start');
setTimeout(() => console.log('After 1 second'), 1000);
console.log('End');
Output
Start End After 1 second
📊

Quick Reference

Use this simple delay function to wait for any number of milliseconds:

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

Then call it inside an async function with await delay(1000) to wait 1 second.

Key Takeaways

Use a Promise with setTimeout to create a delay function.
Use async/await to pause code execution for 1 second.
setTimeout alone does not pause code; it schedules a callback.
Always wrap setTimeout in a Promise for waiting inside async functions.
Use await delay(1000) to wait exactly 1 second.