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); } ...
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).
source share