为什么没有' setInterval()'叫停?

时间:2018-04-14 04:27:14

标签: javascript clearinterval

我已经解决了有关此主题的其他问题并尝试了解决方案。我找不到错误。所以我认为,这肯定是一个明显的错误。任何帮助将不胜感激。

var interval = 0; 

function repeat(time, bool) {
    var interval = setInterval(choose, time * 1000);

    function stopRepeat () {

        console.log("im trying to stop");
        clearInterval(interval);
    }

    if (bool) {
        stopRepeat();
    }
}

我试图阻止"正在登录。所以这意味着clearInterval()是不起作用的。我也尝试将其称为window.interval,但这没有什么区别。

我还记录了它应该清除后的间隔,它只是产生相同的间隔,而不是一个清除的间隔。

谢谢!

2 个答案:

答案 0 :(得分:0)

所以我要先用评论来分析你的代码。

ObjectOutputStream

有很多方法可以试试这个,我会做一些修改。

/*
* First this declaration (var interval=0) is redundant as it is re-declared in the 
* repeat function
*/
var interval = 0; 

function repeat(time, bool) {
    var interval = setInterval(choose, time * 1000);

    function stopRepeat () {

        console.log("im trying to stop");
        clearInterval(interval);
    }
    /*
    * Lets assume bool is true.
    * StopRepeat is called immediately and your interval function never gets 
    * to execute nor does your choose function even gets called.

    * Now lets assume bool is even false.
    * StopRepeat never gets called and there is not way of clearing the interval
    */
    if (bool) {
        stopRepeat();
    }
}

答案 1 :(得分:-1)

您只需创建两次相同的变量。它应该是这样的:

var interval = setInterval(选择,时间* 1000)

var interval = null;

function repeat(time, bool) {
    interval = setInterval(choose, time * 1000);

    if (bool) {
        stopRepeat();
    }
}


function stopRepeat () {
    console.log("im trying to stop");
    clearInterval(interval);
}