Using setInterval() and setTimeout() with JavaScript
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: Animation, Front End, JavaScript, setInterval, setTimeout
setInterval() and setTimeout() functions are the quickest solutions to loop functions with JavaScript, often used for a simple animation effects.
For example, setInterval(function(){functionA()}, 1000) executes functionA() every second. On the other hand, setTimeout(function(){functionA()}, 1000) executes functionA() once after waiting for 1 seconds.
Both can be stopped by clearInterval() and clearTimeout() by passing the returned values from respective functions.
setTimeout() can be used to loop functions recursively. The difference from using setInterval() is that the recursive way with setTimeout() calls the function next time only when the first function completes the execution. setInterval() calls the function next time regardless of the execution completion as soon as the time is up. If your function needs to complete the execution before the subsequent call (e.g. AJAX call), it is better to use setTimeout() recursively.
Note that neither timer does not guarantee 100% precision. If the precision is critical, they are not recommended to use.
Let’s have a look at examples.
(1) Counter
The function below display the count from 10 to 0 and goes back to 10. setInterval() is called when the window is loaded.
(2) Button Flashing
Cheap, but effective, trick to flash the button by changing the button color through CSS.
.yellow-button{ background-color: yellow; .pink-button { background-color: pink; }
(3) AJAX call loop
As I mentioned before, when you want to ensure the function to complete execution and can be lenient to the timing of execution, it is better to use setTimeout() recursively. In this example, the function is doing AJAX call to get data from an API endpoint (using JSONPlaceholder). In this way, it only executes the function next time after AJAX call completes.
(4) Header Text Slider
This moves a header text from left to right by changing the left CSS property. Another easy and effective trick. The similar animation reference can be found here.
(5) Header Animation
When you first visit the website, it loads the first header text. Then subsequently, changes text every second. After 3 seconds, the animation finishes until the page is loaded again. This is another easy and effective trick that many websites use.