I have a function that displays words at various speeds. The function starts OK, but I can’t seem to get the code right to stop it again.
I know I have to use clearInterval and I assume that this is to clear the var myTimer – but I can’t get this to work.
Any help would be appreciated
HTML
<input type="button" value="Start" onclick="wpm($numberWords,$speed)" />
<input type="button" value="Stop" onclick="stopWpm()" />
JS
var myTimer;
function wpm(numberWords,speed) {
var input = new Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s");
var output = new Array();
for (var i = 0; i < input.length; i += numberWords) {
output.push(input.slice(i, i + numberWords).join(" "));
}
var i=0;
var myTimer =setInterval(timer,speed); //1000 will run it every 1 second
function timer() {
document.getElementById("timer").innerHTML = output[i];
i++;
if (i == output.length){
clearInterval(myTimer);
}
}
}
function stopWpm() {
clearInterval(myTimer);
}
you have
myTimer; as a global var and withinwpm()you have redeclared it try removing thevarfrommyTimerwithinwpm()function