1

これはこの質問のフォローアップであり、コードをx秒ごとに繰り返す方法を見つけました。これを変えることができるイベントを作ることは可能ですか?つまり、これを繰り返すかどうかを制御するためのチェックボックスがあるので、次のようなものが必要だと考えました。

$(checkbox).bind("change", function() {
    switch(whether if it is ticked or not) {
        case [ticked]:
            // Make the code repeat, while preserving the ability to stop it repeating
        case [unticked]:
            // Make the code stop repeating, while preserving the ability to start again
    }
});

何を入れたらいいのかわからないcase

4

3 に答える 3

2

間隔を停止および開始することができます。

var timer;

function start() {
  timer = window.setInterval(function(){
    // do something
  }, 1000);
}

function stop() {
  window.clearInterval(timer);
}

start();

$(checkbox).bind("change", function() {
  if ($(this).is(':checked')) {
    start();
  } else {
    stop();
  }
});

または、間隔がコードをスキップするようにフラグを設定することもできます。

var enabled = true;

var timer = window.setInterval(function(){
  if (!enabled) {
    // do something
  }
}, 1000);

$(checkbox).bind("change", function() {
  enabled = $(this).is(':checked');
});
于 2012-11-10T20:08:56.277 に答える
2

setInterval 関数を変数に割り当てることでそれを行うことができます。

var interval = setInterval(function() {  }, 1000);

そして、次の方法でsetIntervalを停止できます

clearInterval(interval);

var interval = setInterval(function() { }, 1000);ps 間隔を開始するには、再度呼び出す必要があります

于 2012-11-10T20:03:00.550 に答える
1
function fooFunc() {
    $('#foo').text(+new Date());
}
var id;
var shouldBeStopped = false;
$('input').change(function() {
    if (shouldBeStopped) 
        clearInterval(id);
    else 
        id = setInterval(fooFunc, 200);

    shouldBeStopped = !shouldBeStopped;
});​

ライブデモ

于 2012-11-10T20:05:00.343 に答える