JavaScript Timers. Here’s Everything You Need To Know

Posted by TotalDC

What is a timer? A timer is a function that lets you to 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 page is loaded or event is triggered. For example you can use timers to change the ad banners on your website at a 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 of time. Syntax of this function looks like this:

setTimeout(function, milliseconds)

As you can see this function accepts two parameters – function to execute and delay parameter which is optional. 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>

Code from the example will display an alert message after 2 seconds on 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. Syntax of this function looks like this:

setInterval(function, milliseconds)

This function accepts two parameters – functions 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() returns unique ID which 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>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: