How to call a function every second in JavaScript?

JavaScript is a powerful programming language that allows developers to create dynamic and interactive web applications. One common requirement in many projects is the need to call a function at regular intervals, such as every second. Whether you’re a beginner or an experienced developer, this guide will provide you with the knowledge you need to implement this feature in your projects.

How to call a function every second in JavaScript?

To call a function at regular intervals you need to use setInterval() method:

setInterval(function() {
	console.log('This message will be logged in console every second');
}, 1000);

Looking at the example above you might be wondering about the second parameter passed to setInterval() method – 1000. This parameter is in milliseconds (thousandths of a second) and indicates the delay between executions of the specified function or code. In this case, this is 1000 milliseconds which is equal to 1 second.

How to stop setInterval() method?

It is important to be mindful of the performance and potential memory leaks when using setInterval(). If the function takes a long time to execute or has side effects, it could cause issues for the browser and the user experience. It’s also important to clear the interval when it’s no longer needed to prevent it from running indefinitely.

When you already started calling a function with setInverval() method and you want to stop it, you can do this by using clearInterval() method:

const myInterval = setInterval(function() {
	console.log('Hi from console log');
}, 1000);

clearInterval(myInterval);

You need to assign setInterval() to some variable to be able to clear it later, by passing this variable as a parameter to clearInterval().

Conclusion

In JavaScript, it’s possible to call a function repeatedly at a certain interval using the setInterval() method. To call a function every second (or any other duration), you can pass the function and the duration in milliseconds as arguments to this function. You can clear the interval when it’s no longer needed by using clearInterval() method.

Leave a Reply

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