简体   繁体   English

clearInterval()不起作用?

[英]clearInterval() not working?

function myFunction(interval) {

    var intervalID = window.setInterval(function () {
        getdetails();
        $('.View').load('alert.php').fadeIn("slow");
    }, 3000);

    if (interval == 1) {
        window.clearInterval(intervalID);
    }
}

when I call myFunction with argument 1 then clearInterval() not clear the setInterval() .I want setInterval() stop its excution when I call myFunction with argument 1. 当我使用参数1调用myFunction时,然后clearInterval()不会清除setInterval() 。当我使用参数1调用myFunction时,我希望setInterval()停止执行它。

The problem is that you are creating a new timer everytime you call the function. 问题是您每次调用该函数时都在创建一个新的计时器。 Modify it like: 像这样修改它:

var intervalID = 0;
function myFunction(interval){
    if(interval == 1) {
        if(intervalID != 0) {
            window.clearInterval(intervalID);
            intervalID = 0;
        }
    }
    else if(intervalID == 0) { // create only if not existing
        intervalID = window.setInterval(function () {
            ...
        });
    }
}

Now, the firts time you call it, it will create the timer. 现在,您将其称为点火时间,它将创建计时器。 Afterwards when you call it with 1 as the argument, it will clear the timer. 然后,当您使用1作为参数调用它时,它将清除计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM