Skip to content

Instantly share code, notes, and snippets.

@arpit
Last active September 10, 2018 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arpit/b7aa0e6d5cc77769ac29f087db75c095 to your computer and use it in GitHub Desktop.
Save arpit/b7aa0e6d5cc77769ac29f087db75c095 to your computer and use it in GitHub Desktop.

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