setTimeout
返回一个值(“计时器句柄”),它是一个除0
. clearTimeout
您可以通过在超时发生之前将该值传递给来取消计时器。
因此,您可以记住您已安排的一个或两个计时器的计时器句柄(取决于您的需要),并且当发生某些事情让您想要取消其中一个计时器时,请clearTimeout
使用相关句柄进行调用。
你问了一个例子。由于我仍然完全不清楚你想在什么时候取消,我猜一下:你想要一个电话overall
来取消任何待处理的电话,mobile
反之亦然:
// Variables to hold the timers
var overallTimer = 0,
mobileTimer = 0;
function overall(){
// If a pending call to mobile exists, cancel it
if (mobileTimer) {
clearTimeout(mobileTimer);
mobileTimer = 0;
}
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
// Schedule a call to ourselves, remember the timer handle
overallTimer = setTimeout(overall,1000);
}
function mobile(){
// If a pending call to overall exists, cancel it
if (overallTimer) {
clearTimeout(overallTimer);
overallTimer = 0;
}
$(".one").hide();
$(".two").show();
$(".three").hide();
$(".four").hide();
// Schedule a call to ourselves, remember the timer handle
mobileTimer = setTimeout(mobile,1000);
}
如果您愿意,您可以将计时器存储在函数中,尽管它并不能真正为您带来太多收益:
function overall(){
// If a pending call to mobile exists, cancel it
if (mobile.timer) {
clearTimeout(mobile.timer);
mobile.timer = 0;
}
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
// Schedule a call to ourselves, remember the timer handle
timer = setTimeout(overall,1000);
}
overall.timer = 0;
function mobile(){
// If a pending call to overall exists, cancel it
if (overall.timer) {
clearTimeout(overall.timer);
overall.timer = 0;
}
$(".one").hide();
$(".two").show();
$(".three").hide();
$(".four").hide();
// Schedule a call to ourselves, remember the timer handle
mobile.timer = setTimeout(mobile,1000);
}
mobile.timer = 0;