DEV Community

Cover image for Let's explore the setTimeout and setInterval methods in JavaScript
Amitav Mishra
Amitav Mishra

Posted on

Let's explore the setTimeout and setInterval methods in JavaScript

The setTimeout() method

The setTimeout() method calls a function after a specified time provided in milliseconds. This method takes a function as a first argument and time in milliseconds as the second argument. You can write your logic inside the function body which will execute after the time you have specified.

For example: Show an alert box after 5 seconds.

setTimeout(()=> {
    alert('Message after 5 seconds');
}, 5000);
Enter fullscreen mode Exit fullscreen mode

To cancel the timer, you can store the timer first in a variable and call the clearTimeout() function by passing the timer as argument.

var timer = setTimeout(()=> {
    alert('Message after 5 seconds');
}, 5000);

clearTimeout(timer);
Enter fullscreen mode Exit fullscreen mode

The setInterval() method

The setInterval() method calls a function at specified interval of time provided in milliseconds. It takes function and time (in milliseconds) as its arguments.

For example: Print a random number every second.

setInterval(() => {
    console.log(Math.random());
}, 1000);
Enter fullscreen mode Exit fullscreen mode

To cancel the interval, you can store the interval first in a variable and call the clearInterval() function by passing the interval as argument.

var interval = setInterval(() => {
    console.log(Math.random());
}, 1000);

clearInterval(interval);
Enter fullscreen mode Exit fullscreen mode

Create a running clock timer

To create a running clock, we need to take help of setInterval() method and Date object. We can get the current time by creating a new Date object.

new Date().toLocaleTimeString(); // 4:50:16 PM
Enter fullscreen mode Exit fullscreen mode

Once we create a Date object, it will give us the information of current date and time, it will not change its value with the passing time. So we need to create a fresh new Date object every time to get the latest date and time.

For this example, we will create a new Date object every second and print that.

var date = setInterval(() => { 
   console.log(new Date().toLocaleTimeString());
}, 1000);
Enter fullscreen mode Exit fullscreen mode

To show the running clock timer on a web page, you can create a div element in HTML and set the it’s innerHTML with the latest time every second.

<div id="time"> </div>
Enter fullscreen mode Exit fullscreen mode
var date = setInterval(() => {
  const element = document.getElementById('time');
  element.innerHTML = new Date().toLocaleTimeString();
}, 1000);
Enter fullscreen mode Exit fullscreen mode

You may also like

Thanks for your time
For more web development blogs, please visit jscurious.com

Top comments (0)