0

2 つの JavaScript 関数があり、どちらもクリック イベントで動作します。関数ごとに、タイムアウト プロパティの設定を使用しました。問題は、最初の関数が呼び出され、2 番目の関数が呼び出された場合、両方のタイムアウトが同時にアクティブになることです。1 つの機能が有効になっているときに、1 つの機能のタイマーを無効にする方法はありますか。

脚本:

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);        
    }

これがシナリオである場合、私は何をすべきですか?両方の機能がアクティブになり、一方が有効になっているときにタイムアウトをオフにする方法がわからないため

4

1 に答える 1

3

setTimeoutは、 以外の数値である値 (「タイマー ハンドル」) を返します0clearTimeoutタイムアウトが発生する前にその値を渡すことで、タイマーをキャンセルできます。

そのため、(必要に応じて) スケジュールしたタイマーの一方または両方のタイマー ハンドルを覚えておくことができ、これらのタイマーの 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;
于 2013-03-27T18:11:25.853 に答える