使用clearInterval来停止一个函数

时间:2011-10-26 08:06:40

标签: javascript

我有一个以不同速度显示单词的功能。该函数启动正常,但我似乎无法使代码正确再次停止它。 我知道我必须使用clearInterval,我认为这是为了清除var myTimer - 但我不能让它工作。

任何帮助将不胜感激

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);
}

2 个答案:

答案 0 :(得分:4)

你有myTimer;作为一个全局变量,在wpm()之内,您已重新声明它,请尝试从var函数中的myTimer删除wpm()

// ...
var i=0;
myTimer = setInterval(timer,speed); //1000 will run it every 1 second
function timer() {
// ...

答案 1 :(得分:0)

I had the same problem and this worked for me:

    var operate = function () { start = setInterval( function(){
    ... 
    }
} , time ); }
    var stop = function () {  clearInterval( start ); }
    return { Start: start, Stop: stop }
    }

使用operate.Start() || operate.Stop()处理