如何在javascript中停止window.setInterval? [英] How do I stop a window.setInterval in javascript?

查看:453
本文介绍了如何在javascript中停止window.setInterval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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


推荐答案

没有内置的暂停功能,但是你可以阻止它,然后用相同的函数开始一个新的间隔。

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

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

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

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

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

Then when you want to stop it, call

 window.clearInterval(intervalId);

在你的情况下,我建议定义 setScreen 单独,而不是在 setInterval 的调用内。这样你只需要使用 intervalId = window.setInterval(setScreen,2000)就可以恢复它。

In your case I'd suggest defining setScreen by 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.

这篇关于如何在javascript中停止window.setInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆