如何在javascript中停止window.setInterval?

Bri*_*ian 26 javascript jquery

我有一个每2000毫秒调用一次的javascript函数.我想停止这一点,这样我就可以让用户在页面上做其他事情而不再调用它.这可能吗?这是每2000ms调用的函数:

window.setInterval(function getScreen (sid) {
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
            document.getElementById("refresh").innerHTML=xmlhttp.responseText;
          }
        }
        xmlhttp.open("POST","getScreen.php?sid="+<?php echo $sid; ?>,true);
        xmlhttp.send();
    },2000);
Run Code Online (Sandbox Code Playgroud)

小智 48

没有内置的"暂停"功能,但您可以将其停止,然后使用相同的功能启动新的间隔.

首先,您需要捕获调用返回的id setInterval:

let intervalId = window.setInterval(...);
Run Code Online (Sandbox Code Playgroud)

然后,当你想要停止它时,请致电

 window.clearInterval(intervalId);
Run Code Online (Sandbox Code Playgroud)

在你的情况下,我建议setScreen自己定义,而不是在调用内部setInterval.这样您就可以intervalId = window.setInterval(setScreen, 2000)在想要恢复时使用.


Tim*_*Tim 29

如果您使用的是jQuery,我会推荐使用插件jQuery Timer

var timer = $.timer(function() {
  alert('This message was sent by a timer.');
}, 2000, true);
Run Code Online (Sandbox Code Playgroud)

然后你可以轻松地暂停计时器:

timer.pause();
Run Code Online (Sandbox Code Playgroud)

并恢复它:

timer.play();
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的提示,它很有用. (2认同)

Tim*_*own 16

通过使用window.setTimeout()而不是更容易做到这一点window.setInterval().以下是我的答案适应这里.

现场演示:http://jsfiddle.net/timdown/Hkzex/

码:

function RecurringTimer(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };

    var resume = function() {
        start = new Date();
        timerId = window.setTimeout(function() {
            remaining = delay;
            resume();
            callback();
        }, remaining);
    };

    this.resume = resume;

    this.resume();
}
Run Code Online (Sandbox Code Playgroud)


jfr*_*d00 5

您无法暂停间隔,但可以停止并重新开始。

var timer = setInterval(xx,tt);

// then some time later
clearInterval(timer);
Run Code Online (Sandbox Code Playgroud)

您只需捕获返回值setInterval()clearInterval()在想要停止时调用它即可。

另一种可以随时停止重复的重复方法是进行重复setTimeout(),然后clearTimeout()停止下一个计时器,或者只是不启动下一个计时器setTimeout()