[英]Cancel Javascript timeout
I have a long process hosted on a Web Server. 我在Web服务器上托管了一个很长的进程。 The thing is triggered from a Web Page, at the click of a button by a user.
只需用户点击按钮,即可从网页触发该事物。 Some Javascript polls regularly via Ajax to check if the operation has completed server side.
一些Javascript定期通过Ajax进行轮询,以检查操作是否已完成服务器端。 To do this, I use
setInterval
, and later on clearInterval
to stop polling. 为此,我使用
setInterval
,稍后使用clearInterval
来停止轮询。
If this takes too long (eg server has crashed), I'd like the client to be informed by some sort of timeout. 如果这需要太长时间(例如服务器崩溃),我希望通过某种超时通知客户端。 I've done some research and found about
setTimeout
. 我做了一些研究,发现了
setTimeout
。 Problem is, if the operation finishes successfully before the timeout, I'd like to cancel this one. 问题是,如果操作在超时之前成功完成,我想取消这个。
PS : I'm targetting IE7/IE8 in particular, but always open to some JQuery PS:我特别针对IE7 / IE8 ,但总是对某些JQuery开放
As long as you store your interval's id in a variable, you can use it to clear the interval at any time. 只要将间隔的id存储在变量中,就可以随时使用它来清除间隔。
var interval = window.setInterval(yourFunction, 10000);
...elsewhere...
window.clearTimeout(interval);
For more information see the Mozilla Documentation's setInterval example . 有关更多信息,请参阅Mozilla文档的setInterval示例 。
Put together a quick JS Fiddle containing a modified version of Mozilla's Example . 将包含Mozilla示例的修改版本的快速JS小提琴组合在一起。
要清除setTimeout,请使用clearTimeout 。
You want two timers (as you said) 你想要两个计时器(如你所说)
If the polling is successful you want to clear both the polling interval and cancel the failure timer. 如果轮询成功,则需要清除轮询间隔并取消故障计时器。 If the expiration timer fires you want to clear the polling interval
如果到期计时器触发,则要清除轮询间隔
var checkCount = 0;
function checkComplete() {
console.log("test " + checkCount);
if (checkCount++ > 10) {
console.log("clearing timeout");
window.clearInterval(pollInterval);
window.clearTimeout(expireTimer);
}
}
function cancelPolling(timer) {
console.log("clearing poll interval");
window.clearInterval(pollInterval);
}
var pollInterval = window.setInterval(checkComplete, 500);
var expireTimer = window.setTimeout(cancelPolling, 10000);
You can fiddle with the checkCount
constant "10" - keep it low to simulate polling success, raise it higher for the timeout to occur before the checkCount is reached, simulating polling failure. 你可以调整
checkCount
常量“10” - 保持低位以模拟轮询成功,将其提高到达到checkCount之前发生的超时,模拟轮询失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.