I am using setInterval(fname, 10000);
to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the us
Try
let refresch = ()=> document.body.style= 'background: #'
+Math.random().toString(16).slice(-6);
let intId = setInterval(refresch, 1000);
let stop = ()=> clearInterval(intId);
body {transition: 1s}
<button onclick="stop()">Stop</button>
clearInterval()
Note, you can start and pause your code with this capability. The name is a bit deceptive, since it says CLEAR, but it doesn't clear anything. It actually pauses.
Test with this code:
HTML:
<div id='count'>100</div>
<button id='start' onclick='start()'>Start</button>
<button id='stop' onclick='stop()'>Stop</button>
JavaScript:
let count;
function start(){
count = setInterval(timer,100) /// HERE WE RUN setInterval()
}
function timer(){
document.getElementById('count').innerText--;
}
function stop(){
clearInterval(count) /// here we PAUSE setInterval() with clearInterval() code
}
If you set the return value of setInterval
to a variable, you can use clearInterval
to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
@cnu,
You can stop interval, when try run code before look ur console browser (F12) ... try comment clearInterval(trigger) is look again a console, not beautifier? :P
Check example a source:
var trigger = setInterval(function() {
if (document.getElementById('sandroalvares') != null) {
document.write('<div id="sandroalvares" style="background: yellow; width:200px;">SandroAlvares</div>');
clearInterval(trigger);
console.log('Success');
} else {
console.log('Trigger!!');
}
}, 1000);
<div id="sandroalvares" style="background: gold; width:200px;">Author</div>