About
In this code snippet, we’ll learn how to use timers in Javascript.
Timers can be used to execute code at certain intervals. When we make a timer we need to specify the function that will be called on each tick and the interval length in milliseconds. We’ll also take a look at delays which opposed to timers only run once.
Let’s see the code example below.
Code:
//Timer.//////////////////////////////////////////////// function timerCallback(){ console.log("I'm spamming the console every 5s."); } //The timerCallback() function will be called every 5000ms or 5s. const timer = window.setInterval(timerCallback, 5000); //The timer can be stopped like so: //window.clearInterval(timer); //////////////////////////////////////////////////////// //Delay.//////////////////////////////////////////////// function delayCallback(){ console.log("I was delayed for 2s."); } //The delayCallback() function will be called(only once) after 5000ms or 5s. const delay = window.setTimeout(delayCallback, 2000); //The delay can be stopped like so: //window.clearTimeout(delay); ////////////////////////////////////////////////////////