Everything You Need To Know About JavaScript Timers

Posted by TotalDC

What are JavaScript timers? A timer is a function that lets you execute a function at a particular time.

By using timers you can delay the execution of code so that it does not get done at the time when the page is loaded or the event is triggered. For example, you can use timers to change the ad banners on your website at regular intervals, etc.

In JavaScript, there are two timer functions – setTimeout() and setInterval(). Let’s continue our JavaScript series and learn everything you need to know about timers in JavaScript.

How To Execute Code After Delay In JavaScript

The setTimeout() function is used to execute a function once after a certain period. The syntax of this function looks like this:

setTimeout(function, milliseconds)

As you can see this function accepts two parameters – the function to execute and the optional delay parameter. Delay is written in milliseconds. Here’s how it works:

<script>
function myFunction() {
    alert('Hello World!');
}
</script>
 
<button onclick="setTimeout(myFunction, 2000)">Click Me</button>

The code from the example will display an alert message after 2 seconds on the click of the button.

How To Execute Code At A Regular Intervals In JavaScript

To do this you can use the setInterval() function. This function will execute a specified piece of code repeatedly at fixed time intervals. The syntax of this function looks like this:

setInterval(function, milliseconds)

This function accepts two parameters – function name and interval in milliseconds. Here’s an example:

<script>
function showTime() {
    let d = new Date();
    document.getElementById("clock").innerHTML = d.toLocaleTimeString();
}
setInterval(showTime, 1000);
</script>
 
<p>The current time on your computer is: <span id="clock"></span></p>

This code will execute the showTime() function repeatedly after 1 second. This function retrieves the current time on your computer and displays it in the browser.

How To Stop Code Execution Or Cancel A Timer In JavaScript

Both setTimeout() and setInterval() return a unique ID that identifies the timer created by these methods.

You can use this ID to disable or clear the timer and stop the execution of the code. Clearing the timer can be done by using clearTimeout() and clearInterval().

Here’s an example of clearTimeout() method:

<script>
let timeoutID;
 
function delayedAlert() {
  timeoutID = setTimeout(showAlert, 2000);
}
 
function showAlert() {
  alert('This is a JavaScript alert box.');
}
 
function clearAlert() {
  clearTimeout(timeoutID);
}
</script>
 
<button onclick="delayedAlert();">Show Alert After Two Seconds</button>
 
<button onclick="clearAlert();">Cancel Alert</button>

Now let’s take a look at the clearInterval() method:

<script>
let intervalID;
 
function showTime() {
    let d = new Date();
    document.getElementById("clock").innerHTML = d.toLocaleTimeString();
}
 
function stopClock() {
    clearInterval(intervalID);
}
 
let intervalID = setInterval(showTime, 1000);
</script>
 
<p>The current time on your computer is: <span id="clock"></span></p>
 
<button onclick="stopClock();">Stop The
 Clock</button>