codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🌐

JavaScript

45 / 65 topics
44JavaScript Callbacks45JavaScript setTimeout and setInterval46JavaScript Promises47JavaScript Promise Chaining48JavaScript async and await49JavaScript Event Loop
Tutorials/JavaScript/JavaScript setTimeout and setInterval
🌐JavaScript

JavaScript setTimeout and setInterval

Updated 2026-05-12
15 min read

JavaScript setTimeout and setInterval

In the world of programming, especially in web development, it's often necessary to delay the execution of a piece of code or to repeat a task at regular intervals. This is where setTimeout and setInterval come into play. These functions allow you to schedule asynchronous code execution, making your applications more dynamic and responsive.

Introduction

setTimeout and setInterval are JavaScript methods that enable you to execute a function after a specified delay or repeatedly at fixed time intervals. They are essential for tasks like animations, delayed responses, periodic updates, and more. Understanding how to use these functions effectively can greatly enhance the interactivity of your web applications.

Core Content

Understanding setTimeout

setTimeout is used to schedule a function to be executed after a specified delay in milliseconds. It takes two parameters: the function to execute and the delay time (in milliseconds).

Basic Syntax

JavaScript
1setTimeout(function, delay);
  • function: The function you want to execute.
  • delay: The number of milliseconds to wait before executing the function.

Example 1: Simple Delayed Execution

Let's create a simple example where we log a message after a delay of 2000 milliseconds (2 seconds).

script.js
1console.log("Starting the script...");
2setTimeout(function() {
3 console.log("This message is logged after 2 seconds.");
4}, 2000);
5console.log("Script execution continues immediately.");
Output
Starting the script...
Script execution continues immediately.
This message is logged after 2 seconds.

In this example, "Starting the script..." and "Script execution continues immediately." are logged almost instantly, while "This message is logged after 2 seconds." appears after a delay of 2 seconds.

Understanding setInterval

setInterval, on the other hand, repeatedly executes a function at fixed time intervals. It also takes two parameters: the function to execute and the interval time (in milliseconds).

Basic Syntax

JavaScript
1setInterval(function, interval);
  • function: The function you want to execute repeatedly.
  • interval: The number of milliseconds between each execution.

Example 2: Repeated Execution

Let's create an example where we log a message every 1000 milliseconds (1 second).

script.js
1let count = 0;
2const intervalId = setInterval(function() {
3 console.log(`Count is ${count}`);
4 count++;
5 if (count === 5) {
6 clearInterval(intervalId);
7 console.log("Interval stopped.");
8 }
9}, 1000);
Output
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Interval stopped.

In this example, the message "Count is X" is logged every second until the count reaches 5. At that point, clearInterval is called to stop the interval.

Common Mistakes and Best Practices

  • Avoid Blocking the Main Thread: Both setTimeout and setInterval are asynchronous, meaning they do not block the main thread. However, if the function you pass to these methods takes a long time to execute, it can still impact performance.

  • Use clearTimeout and clearInterval: Always ensure that you clear your timers when they are no longer needed. This prevents memory leaks and unnecessary resource consumption.

  • Understand Timing Precision: JavaScript's timing functions are not perfect due to the single-threaded nature of the language. The actual delay or interval may vary slightly depending on system load and other factors.

Practical Example

Let's create a practical example that combines both setTimeout and setInterval. We'll build a simple countdown timer that starts from 10 seconds and counts down to zero, logging each second.

countdown.js
1let timeLeft = 10;
2const intervalId = setInterval(function() {
3 console.log(`Time left: ${timeLeft} seconds`);
4 timeLeft--;
5 if (timeLeft === 0) {
6 clearInterval(intervalId);
7 console.log("Countdown finished!");
8 }
9}, 1000);
Output
Time left: 10 seconds
Time left: 9 seconds
Time left: 8 seconds
Time left: 7 seconds
Time left: 6 seconds
Time left: 5 seconds
Time left: 4 seconds
Time left: 3 seconds
Time left: 2 seconds
Time left: 1 seconds
Countdown finished!

In this example, the countdown starts from 10 and decrements every second until it reaches zero. The clearInterval function is used to stop the interval when the countdown finishes.

Summary

ConceptDescription
setTimeoutExecutes a function after a specified delay in milliseconds.
setIntervalRepeatedly executes a function at fixed time intervals.
clearTimeoutStops the execution of a scheduled setTimeout.
clearIntervalStops the repeated execution of a scheduled setInterval.
  • Use setTimeout for one-time delays.
  • Use setInterval for periodic tasks.
  • Always clear your timers when they are no longer needed to prevent memory leaks.

What's Next?

Now that you've learned about setTimeout and setInterval, the next step is to explore JavaScript Promises. Promises provide a more structured way of handling asynchronous operations, making your code cleaner and easier to manage. Continue to the next topic to dive deeper into Promises and how they can improve your JavaScript applications.

nextTopic.js
1// Example of using a Promise
2const myPromise = new Promise((resolve, reject) => {
3 setTimeout(() => {
4 resolve("Promise resolved!");
5 }, 2000);
6});
7
8myPromise.then(result => {
9 console.log(result);
10});
Output
Promise resolved!

PreviousJavaScript CallbacksNext JavaScript Promises

Recommended Gear

JavaScript CallbacksJavaScript Promises