0

おそらく最も明確なタイトルではありませんが、ここにあります-ページに2つの独立したカウントダウンを表示し、それぞれの開始値のユーザー入力を受け入れる必要があります。一方がゼロに達すると、もう一方が開始してゼロまでカウントダウンします。このためのコードは以下のとおりで、期待どおりに機能しています。

変数の開始値をチェックするTimer1関数を呼び出します。開始値が存在する場合は、カウントが開始されます。カウントがゼロになったら、間隔をクリアし、表示を開始値にリセットし、値が割り当てられている場合は2番目のタイマーを起動します。

    function Timer1() {
        var gDuration = goTime;
        countdown = setInterval(function () {
            if (gDuration >= 0) {
                $("#durationValue").html(ToTime(gDuration));
                gDuration--;
            }
            else {
                clearInterval(countdown);
                $("#durationValue").html(ToTime(goTime));
                if (restTime != 0) {
                    Timer2();
                }
            }
        }, 1000);
    }

    function Timer2() {
        var rDuration = restTime;
        countdown = setInterval(function () {
            if (rDuration >= 0) {
                $("#restValue").html(ToTime(rDuration));
                rDuration--;
            }
            else {
                clearInterval(countdown);
                $("#restValue").html(ToTime(restTime));
            }
        }, 1000);
    }

次のステップは、そのプロセスを設定された数のループで実行できるようにすることです。Timer1のsetIntervalをforループでラップしようとしましたが、機能しません。これについてもっとうまくいく方法はありますか?

4

2 に答える 2

1

for-loops don't work well with asynchronous stuff. Just make it a counter with an end condition as you have demonstrated with g/rDuration already.

With some callback abstractions, and heavy continuation-passing-style:

function timer(el, duration, interval, callback) {
    var countdown = setInterval(function() {
        if (duration-- >= 0) {
            el.text(ToTime(duration));
        } else {
            clearInterval(countdown);
            callback();
        }
    }, interval);
}

var goTime = …, restTime = …;
function t1(cb) {
    timer($("#durationValue"), goTime, 1000, cb);
}
function t2(cb) {
    timer($("#restValue"), restTimer, 1000, cb);
}
var loops = …;
(function loop(cb) {
    t1(function(){
        t2(function() {
            if (loop-- >= 0)
                loop(cb);
            else
                cb();
        });
    });
})(function() {
    alert("finished!");
});
于 2012-12-21T03:38:35.070 に答える
0

The easiest thing I can think of is to have your Timer functions have a parameter with the current iteration. Increment that value whenever one timer starts another time. And use that value to determine if it should indeed start the next timer.

于 2012-12-21T03:37:03.387 に答える