Categories
JavaScript JavaScript Basics

Add a Timer to Run Code Between Specified Time Intervals With JavaScript

Spread the love

Adding a timer is easy with JavaScript. There’re 2 methods for adding a timer into our JavaScript app. One is the setTimeout function. The other is the setInterval function.

Thr setInterval function lets us run code after a given delay in milliseconds repeatedly. It’s queued to be run after the given amount of delay time and then it’ll run the callback we pass in into the main thread.

For instance, we can use it as follows:

setInterval(() => console.log('hi'), 1000);

In the code above, we passed in a callback function as the first argument of the time setInterval function and a 1000 ms interval as the second argument.

Then we should see 'hi' logged in the console log output after every second.

We can also pass in arguments to the callback by passing in more arguments after the second argument. They can be accessed in the callback in the same order.

For instance, we can do that as follows:

setInterval((greeting) => console.log(greeting), 1000, 'hi');

In the code above, we passed 'hi' as the 3rd argument of setInterval, which will let us access the argument from the greeting parameter.

Therefore, we’ll see 'hi' logged in the console log output since greeting is 'hi'.

setInterval also takes a string instead of a callback as the first argument, where the string has the code that a callback normally has.

However, this prevents performance optimizations from being done and also presents security issues since attackers can potentially inject their own code as a string into the setInterval if we aren’t careful.

If we don’t need the timer any more, we can cancel the timer by calling the clearInterval function which takes the timer ID object that’s returned by setInterval.

For instance, we can do that as follows:

const timer = setInterval((greeting) => console.log(greeting), 1000, 'hi');
clearInterval(timer);

Since we called clearInterval immediately after calling setInterval, the callback won’t be called since we disposed of our timer with clearInterval.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *