1

This is a followup to this question, where I found out how to make code be repeated every x seconds. Is it possible to make an event that can change this? I.e. I have a checkbox which is meant to control whether this is repeated or not, so I figured I'd need something like this:

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

I have no idea what I could put in the cases.

Community
  • 1
  • 1
Bluefire
  • 12,429
  • 22
  • 67
  • 111

3 Answers3

2

You can do it by assigning your setInterval function to a variable.

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

and then you can stop setInterval by

clearInterval(interval);

p.s. to start your interval you need to call var interval = setInterval(function() { }, 1000); again

Kirill Ivlev
  • 11,870
  • 5
  • 25
  • 30
2

You can either stop and start the interval:

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

Or you can have a flag causing the interval to skip the code:

var enabled = true;

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

$(checkbox).bind("change", function() {
  enabled = $(this).is(':checked');
});
Guffa
  • 666,277
  • 106
  • 705
  • 986
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;
});​

Live DEMO

gdoron is supporting Monica
  • 142,542
  • 55
  • 282
  • 355