Ad space (banner)
🟨JavaScript Lessons
Lesson 57 / 69

Waiting a Fixed Amount of Time (setTimeout and await)

In this lesson you'll learn how to combine setTimeout with await to pause processing for a set amount of time, so you can write programs that control timing. This is for people searching "JavaScript setTimeout await."

Wrapping setTimeout() in a Promise and using await lets you pause execution for a specified amount of time. This is used for things like adjusting animation timing, or spacing out a series of operations. setTimeout() is originally a mechanism that takes a callback function, but wrapping it in a Promise makes it usable together with await.

The sample code creates a Promise, using new Promise((resolve) => setTimeout(resolve, 500)), that completes after 500 milliseconds, and waits on it with await. Check that "Starting processing" is displayed, and then, after a short pause, "Executed after 0.5 seconds" appears.

A common beginner stumbling block is that setTimeout() on its own can't be awaited — it needs to be wrapped in a Promise. Writing setTimeout(resolve, 500) means "call the resolve function (a function that signals the processing is complete) after 500 milliseconds" — understanding this mechanism will also deepen your overall understanding of async code.

This is a technique frequently applied in real work too — for example, waiting a bit before retrying to avoid overloading a server with excessive requests. Get a feel for "waiting," the fundamental operation of asynchronous processing, through this simple example.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)