Javascript set / clearinterval not working

How can I stop the interval in javascript?

Why does the interval not stop?

setInterval(alarm, 500); window.clearInterval(alarm); 

also tried:

 window.setInterval(alarm, 500); window.clearInterval(alarm); 

always the same problem :(

still not working:

 var switc = 1; getValue(); function getValue (){ if(switc == 1){ var myTimer = window.setInterval(alarm, 500); } else if(switc == 0){ window.clearInterval(myTimer); } } function alarm(){ console.log("test"); } 
+2
source share
4 answers

When you call setInterval, it returns the integer that you use to cancel the event. Store this in a variable and use this variable to cancel the event.

 var myTimer = window.setInterval(alarm, 500); window.clearInterval(myTimer); 

EDIT:

Your code does not work, since myTimer is a local variable and reset every time you call a function!

Make global.

 var myTimer = null; function getValue (){ if(switc == 1){ myTimer = window.setInterval(alarm, 500); } ... 

MDN Docs: window.setInterval

Calls a function or executes a code fragment several times, with a fixed time delay between each call to this function.

Syntax

 var intervalID = window.setInterval(func, delay[, param1, param2, ...]); var intervalID = window.setInterval(code, delay); 

Where

  • intervalID is the unique identifier for the interval, which you can pass to clearInterval ().
  • func is the function you want to call repeatedly.
  • code in alternative syntax is a line of code that you want to execute repeatedly (using this syntax is not recommended for the same reasons as using eval ())
  • delay is the number of milliseconds (thousandths of a second) that the setInterval () function must wait before each call to the func function. As with setTimeout, there is minimal delay. Note that passing additional function parameters in the first syntax does not work in Internet Explorer. If you want to enable this feature in this browser, you must use a compatibility code (see paragraph on callback arguments).
+10
source

This code shows a misunderstanding of the API. The setInterval() function takes two arguments: a function to call and a number representing the number of milliseconds between calls. The function returns a token (number) that identifies a specific interval timer. The token can be passed to clearInterval() to cancel the timer.

+2
source

You are trying to clear a non-existent interval. Assign the identifier returned by setInterval () to a variable and use it in clearInterval ().

In your case, an alarm is a function that is executed, not id intervals

 var interval = setInterval(alarm, 500); clearInterval(interval); 
+1
source
 var timer = setInterval(alarm, 500); Window.clearInterval(timer); function alarm() { // Do stuff } 

You need to store the interval handle in a variable so that you can later refer to it when you want to clear / stop it.

+1
source

Source: https://habr.com/ru/post/1257920/


All Articles