如何停止JavaScript中的window.setInterval?

我有一个JavaScript函数,每2000毫秒被调用。 我想停止这个,所以我可以让用户在页面上做其他事情,而不再被调用。 这可能吗? 这是每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); 

没有内置的“暂停”function,但可以停止,然后用相同的function启动一个新的时间间隔。

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

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

然后当你想停止它,打电话

  window.clearInterval(intervalId); 

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

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

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

那么你可以轻松地暂停计时器:

 timer.pause(); 

并恢复它:

 timer.play(); 

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

您不能暂停间隔,但可以停止并重新启动。

 var timer = setInterval(xx,tt); // then some time later clearInterval(timer); 

你只需要捕获setInterval()的返回值,当你想停止它时调用clearInterval()

另一种重复的方式是可以随时停止重复执行setTimeout() ,然后使用clearTimeout()来停止下一个定时器,或者不要启动下一个setTimeout()

不要重申任何东西

只需添加一个告诉间隔不要做任何事情的类。 例如:在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> 
 var intervalId = window.setInterval(code); window.clearInterval(intervalId);