0
0
JavascriptConceptBeginner · 3 min read

What is setTimeout in JavaScript: Explanation and Examples

setTimeout is a JavaScript function that delays running a piece of code for a specified time in milliseconds. It schedules a task to run once after the delay, allowing you to pause actions without stopping the whole program.
⚙️

How It Works

Imagine you want to remind yourself to check the oven after 5 minutes. Instead of watching the clock constantly, you set a timer that rings once after 5 minutes. setTimeout works similarly in JavaScript: it sets a timer to run a function once after a delay you choose.

When you call setTimeout, JavaScript starts counting down the milliseconds you specify. Once the time is up, it runs the function you gave it. Meanwhile, the rest of your code keeps running without waiting.

This helps keep your program smooth and responsive, like setting reminders without stopping everything else.

💻

Example

This example shows how to print a message after 2 seconds using setTimeout.

javascript
console.log('Start');
setTimeout(() => {
  console.log('This runs after 2 seconds');
}, 2000);
console.log('End');
Output
Start End This runs after 2 seconds
🎯

When to Use

Use setTimeout when you want to delay an action without freezing your program. For example:

  • Showing a message after a short pause.
  • Waiting before retrying a network request.
  • Creating simple animations by delaying steps.
  • Scheduling reminders or alerts.

It’s useful whenever you want to wait a bit before doing something, but still keep your app running smoothly.

Key Points

  • setTimeout runs a function once after a delay.
  • The delay is in milliseconds (1000 ms = 1 second).
  • It does not pause the whole program, just schedules a future task.
  • You can cancel it with clearTimeout if needed.

Key Takeaways

setTimeout schedules a function to run once after a set delay in milliseconds.
It allows your program to keep running while waiting for the delayed task.
Use it to delay actions like showing messages, retries, or animations.
You can stop a scheduled setTimeout with clearTimeout if needed.