How to call a function every second in JS [SOLVED]


Written By - Olorunfemi Akinlua
Advertisement

Introduction

In this article, we'll be discussing how to call a function every second in JavaScript. This can be a very useful technique for keeping track of time, or for running a repetitive task. In this article, we'll be using the setInterval() function to achieve this.

 

setInterval or setTimeout, which one to use?

One of the simplest kinds of asynchrony is when you want to run some code after a certain amount of time has elapsed. As we saw in §11.10, you can do this with the setTimeout() function:

setTimeout(checkForUpdates, 60000);

The first argument to setTimeout() is a function and the second is a time interval measured in milliseconds. In the preceding code, a hypothetical checkForUpdates() function will be called 60,000 milliseconds (1 minute) after the setTimeout() call. checkForUpdates() is a callback function that your program might define, and setTimeout() is the function that you invoke to register your callback function and specify under what asynchronous conditions it should be invoked.

setTimeout() calls the specified callback function one time, passing no arguments, and then forgets about it. If you are writing a function that really does check for updates, you probably want it to run repeatedly. You can do this by using setInterval() instead of setTimeout():

// Call checkForUpdates in one minute and then again every minute after that
let updateIntervalId = setInterval(checkForUpdates, 60000);

// setInterval() returns a value that we can use to stop the repeated
// invocations by calling clearInterval(). (Similarly, setTimeout()
// returns a value that you can pass to clearTimeout())
function stopCheckingForUpdates() {
    clearInterval(updateIntervalId);
}
NOTE:

Both the setTimeout() and the setInterval() methods are ancient parts of JavaScript. However, they are not obsolete or deprecated. For more complex scenarios, you should web workers rather than roll your own custom solutions built on setTimeout() or setInterval(). However, both methods are still acceptable.

 

Use setInterval method to call a function every second

On how to call a function every second in JavaScript, the setInterval method is your best approach to achieving this. All we need is the function we want to call every second and the timeframe we want to repeat the function call. Just like setTimeout method, only the function we want to call at an interval is required, but the delay parameter (default is 0) is needed if we want to make sure to call the function at a specified interval.

Via the Windows and Worker interface, the setInterval method calls a fixed time frame repeatedly, and the method returns an interval ID that can be used to identify the operation to be canceled out by the clearInterval method (similar to clearTimeout)

setInterval(function, delay, arg1, ..., argN)

The arg1...argN are the arguments that will be passed on to the function. Now, let’s illustrate the setInterval method by logging the date and time every second. We create a function named timeAndDate that logs the Date object and passes the same function to the setInterval method at 1000 milliseconds (which corresponds to 1 second). With this, we have called a function every second in JavaScript.

Advertisement
const timeID = setInterval(timeAndDate, 1000);

function timeAndDate() {
    console.log(new Date());
}

Output

2022-11-09T05:21:20.263Z
2022-11-09T05:21:21.274Z
2022-11-09T05:21:22.277Z
2022-11-09T05:21:23.291Z
2022-11-09T05:21:24.291Z

The above output will continue for as long as possible. If we want to clear out the interval, we can make use of the clearInterval method. All in all, to call a function every second, the code template above is a named function, all you need is add your own logic to your function and pass it to the setInterval method. You can also make use of anonymous functions as seen below, and the value "Date" is an argument passed to the anonymous function.

const timeID = setInterval(
    (arg) => {
        console.log(`${arg}: ${new Date()}`);
    },
    1000,
    "Date"
);

Output

Date: Wed Nov 09 2022 06:21:48 GMT+0100 (West Africa Standard Time)
Date: Wed Nov 09 2022 06:21:49 GMT+0100 (West Africa Standard Time)
Date: Wed Nov 09 2022 06:21:50 GMT+0100 (West Africa Standard Time)
Date: Wed Nov 09 2022 06:21:51 GMT+0100 (West Africa Standard Time)
Date: Wed Nov 09 2022 06:21:52 GMT+0100 (West Africa Standard Time)

 

Summary

Whether it is an anonymous function or a typical callback function, the setInterval method allows us to repeatedly call a function within a specified time frame, and this operation can be cleared out via the clearInterval method. So, to call a function every second, we need to pass the function to the setInterval method and pass a delay parameter of 1000 milliseconds equivalent to 1 second.

 

References

setInterval() - Web APIs | MDN (mozilla.org)
What's the easiest way to call a function every 5 seconds

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment