Skip to content

Instantly share code, notes, and snippets.

@arpit
Last active Sep 10, 2018
Embed
What would you like to do?

setInterval and clearInterval are top level functions part of JavaScript

What does that mean?

Basically these functions are defined by the window object. You can either call this function like window.setInterval( ... ) or just setInterval( ... )

setinterval is used to call any function again and again every few milliseconds.

It takes 2 parameters: the function to call periodically and what the duration between the calls is. So for example:

function callMe(){
 console.log("Hello")
}

setInterval(callMe, 1000)

will continuously call the callMe function every 1000 milliseconds (1 second)

https://www.w3schools.com/jsref/met_win_setinterval.asp

ClearInterval

setInterval returns an integer. So if you want to stop the continous loop thats calling the function again and again, just call clearInterval( whatever_id_was_returned )

So example:

function callMe(){
 console.log("Hello")
}

let intv = setInterval(callMe, 1000)

document.querySelector("#my_button").addEventListener( "click", function(){
                                                        clearInterval(intv)
                                                       }) 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment