[英]How to clear time out in javascript function
我有兩個JavaScript函數,都可以在click事件上使用。 對於每個功能,我都使用了set time out屬性。 問題是,如果調用了第一個函數而調用了第二個函數,則兩個超時都一起激活。 啟用一項功能時,有什么方法可以禁用該功能的計時器。
腳本:
function overall(){
$(".one").show();
$(".two").hide();
$(".three").hide();
$(".four").hide();
setTimeout(overall,1000);
}
function mobile(){
$(".one").hide();
$(".two").show();
$(".three").hide();
$(".four").hide();
setTimeout(mobile,1000);
}
如果是這種情況,我該怎么辦? 因為這兩個功能都將被激活,並且我不知道如何在啟用一個功能時關閉超時
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.