Categories
JavaScript Answers

How to Create a JavaScript setInterval Callback Function that Clears Itself?

Spread the love

Sometimes, we want to create a JavaScript setInterval callback function that clears itself.

In this article, we’ll look at how to create a JavaScript setInterval callback function that clears itself.

Create a JavaScript setInterval Callback Function that Clears Itself

To create a JavaScript setInterval callback function that clears itself, we can call the clearInterval function with the timer handle as the argument.

For instance, we can write:

const myInterval = setInterval(() => {  
  console.log('hello')  
  clearInterval(myInterval);  
}, 50);

to call setInterval with a callback that logs 'hello' and then calls clearIntrval with the timer handle returned by setInterval to clear the timer.

The 2nd argument is set to 50 so that the callback runs every 50 milliseconds.

But the callback will only run once since we called clearInterval with myInterval to stop the timer.

Conclusion

To create a JavaScript setInterval callback function that clears itself, we can call the clearInterval function with the timer handle as the argument.

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 *