如何在 javascript 中停止 window.setInterval?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7279567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:36:37  来源:igfitidea点击:

How do I stop a window.setInterval in javascript?

javascriptjquery

提问by Brian

I have a javascript function that is called every 2000ms. I want to stop this so I can have the user do other things on the page without it being called again. Is this possible? Here is the function that gets called every 2000ms:

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

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

回答by Facebook Staff are Complicit

There's no built-in "pause" function, but you can stop it, and then start a new interval with the same function.

没有内置的“暂停”功能,但您可以停止它,然后使用相同的功能开始一个新的间隔。

First, you need to capture the id returned by the call to setInterval:

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

let intervalId = window.setInterval(...);

Then when you want to stop it, call

然后当你想停止它时,调用

 window.clearInterval(intervalId);

In your case I'd suggest defining setScreenby itself, and not inside of the call to setInterval. This way you can just use intervalId = window.setInterval(setScreen, 2000)when you want to resume it.

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

回答by Tim

If you are using jQuery I would recommend the plugin jQuery Timer

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

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

Then you can easily pause the timer:

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

timer.pause();

And also resume it:

并恢复它:

timer.play();

回答by Tim Down

It's easier to do this by using window.setTimeout()instead of window.setInterval(). The following is adapted from my answer here.

使用window.setTimeout()代替更容易做到这一点window.setInterval()。以下内容改编自我在这里的回答。

Live demo: http://jsfiddle.net/timdown/Hkzex/

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

Code:

代码:

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

回答by jfriend00

You can't pause an interval, but you can stop it and restart it.

您无法暂停间隔,但可以停止并重新启动它。

var timer = setInterval(xx,tt);

// then some time later
clearInterval(timer);

You just have to capture the return value from setInterval()and call clearInterval()on it when you want to stop it.

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

The other way to do a repeat that you can stop repeating at any time is to do a repeated setTimeout()and then clearTimeout()to stop the next timer or just don't kick off the next setTimeout().

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

回答by Aart den Braber

Do not re-declare anything

不要重新声明任何东西

Simply add a class that tells the interval not to do anything. For example: on hover.

只需添加一个类,告诉间隔不要做任何事情。例如:悬停。

var i = 0;
window.setInterval(function() { //declare new function
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
    $('#showCount').html(i++); //just for explaining and showing
  }
}, 500);

$('#counter').hover(function() { //mouse enter
    $(this).addClass('pauseInterval');
    $('#counting').text('Stopped counting...');
  },function() { //mouse leave
    $(this).removeClass('pauseInterval');
    $('#counting').text('Counting...');
  }
);
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="counter"><span id="counting">Counting...</span> | <span id="showCount"></span></div>

回答by Sven van de Scheur

Don't use setInterval(), especially when dealing with network (XHR/fetch) calls.There is no guarantee that your request will be finished on time but setTimeout()won't wait to fire up the next one opening more and more connections.

不要使用setInterval()尤其是在处理网络(XHR/fetch)调用时。不能保证您的请求会按时完成,但setTimeout()不会等待下一个打开越来越多的连接。

Simply use a setTimeout() that, with a simple if statement reschedules itself.

只需使用 setTimeout() ,通过简单的 if 语句重新安排自身。


function updateContent() {
    someFunctionReturningAPromise()
        .then(() => {
            if (continue) {
                setTimeout(updateContent), 2000);
            }
        })
        .catch(e => console.log(e));
}

updateContent()

回答by Deepika Patel

var intervalId = window.setInterval(code);
window.clearInterval(intervalId);