setTimeout
は、 以外の数値である値 (「タイマー ハンドル」) を返します0
。clearTimeout
タイムアウトが発生する前にその値を渡すことで、タイマーをキャンセルできます。
そのため、(必要に応じて) スケジュールしたタイマーの一方または両方のタイマー ハンドルを覚えておくことができ、これらのタイマーの 1 つをキャンセルしたくなるようなことが起こった場合は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;