Normally when we write code, the code is executed in sequence right after each other.But once in a while we want a piece of code to be executed a bit later, with a delay. Or maybe we want to run a piece of code again and again until something happens or the user does something, like an interval.
Timers are used to execute code after a specified amount of time has passed. There are two types of timers in JavaScript. setTimeout() and setInterval().
​
Let's look at setTimeout(). This is a method that executes a function after a specified amount of time has passed. The method takes two arguments: a function to execute, and the time to wait before executing the function (in milliseconds). Here's an example of setTimeout():
​
​
Now, let's look at setInterval(). This is a method that repeatedly executes a function at a specified interval. The method takes two arguments: a function to execute, and the time interval (in milliseconds) at which to execute the function. Here's an example of setInterval():
Timers can be useful for a variety of purposes, such as implementing a delay before executing a function, creating animations, or updating data at a regular interval.
Important! It's important to use timers carefully to avoid memory leaks. By not paying enough attention to implementing timers can have a negative impact on your web-application.
​
If a timer is set to repeat indefinitely with setInterval(), it's important to clear the timer with clearInterval() when it's no longer needed and you (or the user) want's to end the interval. If not, the timer will continue to execute and consume memory, potentially causing a memory leak.
And the same with timeout, if a timer is set with setTimeout(), it's important to clear the timer with clearTimeout() when it's no longer needed.
​
Here's we look at an example of how to use clearInterval() to stop a repeating timer.
By properly managing timers in your JavaScript code, you can avoid memory leaks and have code that runs smoothly. Having problems with timers will cause some frustration as it can result in memory leaks, bugs and code/animations that is not running smoothly.