Javascript Timer

Code Snippets Timer
Share:

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);
////////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger