JavaScript provides built-in timer functions that allow developers to delay the execution of code or run code repeatedly at specific intervals. Two important timer functions in JavaScript are setTimeout() and setInterval().
These functions are widely used in web development for creating animations, showing notifications, refreshing content, and running background tasks.
What is setTimeout()?
The setTimeout() function executes a piece of code once after a specified delay. The delay is measured in milliseconds.
Syntax of setTimeout()
- function – The code that will execute.
- delay – Time in milliseconds before the function runs.
Example of setTimeout()
Hello after 2 seconds
In this example, the message will appear after a delay of 2000 milliseconds (2 seconds).
Stopping setTimeout()
A timer created using setTimeout() can be cancelled using clearTimeout().
The timer is cancelled before execution.
What is setInterval()?
The setInterval() function executes a piece of code repeatedly at a fixed time interval.
Syntax of setInterval()
- function – The code to execute repeatedly.
- interval – Time in milliseconds between each execution.
Example of setInterval()
Running every second
Stopping setInterval()
To stop a repeating timer, developers use clearInterval().
The repeating timer stops.
Difference Between setTimeout() and setInterval()
- setTimeout() runs the function only once after a delay.
- setInterval() runs the function repeatedly at fixed intervals.
- setTimeout() is used for delayed execution.
- setInterval() is used for repeated tasks.
Conclusion
setTimeout() and setInterval() are essential JavaScript timer functions used to control when code runs. They help developers create delays, animations, automatic updates, and background tasks.
Understanding these timers is important for working with asynchronous behavior and dynamic user interfaces in modern web applications.
In the next tutorial, you will learn about JavaScript Fetch API, which allows developers to retrieve data from servers using HTTP requests.

