Possible Duplicate:
JS - How to clear interval after using setInterval()
I have a function that changes the font-family
of some text every 500 ms using setInterval
(I made it just to practice JavaScript.) The function is called by clicking on an "on" button and the interval is supposed to be cleared using a separate button, "off". However, the "off" button doesn't actually clear the interval, it just continues. I suspect that this has something to do with scope but I'm not sure how to write it any other way. Also, I don't want to do this with jQuery because, after all, I'm doing it to learn.
<body> <p><span id="go" class="georgia">go</span> Italian</p> <p> <button id="on" type="button" value="turn on">turn on</button> <button id="off" type="button" value="turn off">turn off</button> </p> <script> var text = document.getElementById("go"); var on = document.getElementById("on"); var off = document.getElementById("off"); var fontChange = function() { switch(text.className) { case "georgia": text.className = "arial"; break; case "arial": text.className = "courierNew"; break; case "courierNew": text.className = "georgia"; break; } }; on.onclick = function() { setInterval(fontChange, 500); }; off.onclick = function() { clearInterval(fontChange); }; </script> </body>
I did make a fiddle to test it, and it turns out clearInterval stops all future execution, even those that have already be queued.
You will notice a simple trick: repeat = repeat || setInterval(reduce, 1000); This will ensure multiple intervals are not registered.
The clearInterval() function in javascript clears the interval which has been set by setInterval() function before that. setInterval() function takes two parameters. First a function to be executed and second after how much time (in ms). setInterval() executes the passed function for the given time interval.
Calling clearInterval() inside setInterval() has no effect But after calling clearInterval(), it will continue to execute.
setInterval
returns an ID which you then use to clear the interval.
var intervalId; on.onclick = function() { if (intervalId) { clearInterval(intervalId); } intervalId = setInterval(fontChange, 500); }; off.onclick = function() { clearInterval(intervalId); };
The setInterval
function returns an integer value, which is the id of the "timer instance" that you've created.
It is this integer value that you need to pass to clearInterval
e.g:
var timerID = setInterval(fontChange,500);
and later
clearInterval(timerID);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With