daveycroqet
daveycroqet

Reputation: 59

setInterval: Why isn't it resetting?

Why doesn't this code work to turn off setInterval? I click an element to start it, and it begins fine (fading in and out a div #content on 5 second intervals). I click an element to stop it, and it just continues to fade in and out on the week=current, even though it loads the proper week initially.

It does not matter whether I separate the function from the jQuery encapsulation. Any help appreciated.

  $out .= '<script type="text/javascript">'."\n";
  $out .= '$(document).ready(function () {'."\n";
  $out .= '  $("span.archives").click(function () {'."\n";
  $out .= '    $("#content").load("update.php?week=" + this.id);'."\n";
  $out .= '    if (this.id == \'current\') {'."\n";
  $out .= '      StartStop(\'on\');'."\n";
  $out .= '    } else {'."\n";
  $out .= '      StartStop(\'off\');'."\n";
  $out .= '    }'."\n";
  $out .= '  });'."\n";

  $out .= '  function StartStop(txt) {'."\n";
  $out .= '    if (txt == \'on\') {'."\n";
  $out .= '      var refresh = setInterval(function() {'."\n";
  $out .= '        $("#content").fadeOut("slow", function() {'."\n";
  $out .= '          $("#content").load("update.php?week=current", function() {'."\n";
  $out .= '            $("#content").delay(250).fadeIn("slow");'."\n";
  $out .= '          });'."\n";
  $out .= '        });'."\n";
  $out .= '      }, 5000);'."\n";
  $out .= '    } else {'."\n";
  $out .= '      clearInterval(refresh);'."\n";
  $out .= '    }'."\n";
  $out .= '  }'."\n";
  $out .= '});'."\n";
  $out .= '</script>'."\n";

Upvotes: 1

Views: 321

Answers (1)

Kobi
Kobi

Reputation: 138017

refresh is defined locally within StartStop, its value isn't saved between calls to StartStop.
Try defining it outside of it, for example:

var refresh;

function StartStop(txt) {
    refresh = setInterval(/* ... */);
}

Also, you may want to clear the previous refresh before creating a new one:

if (txt == 'on') {
    if(refresh) clearInterval(refresh);
    refresh = setInterval(/* ... */);
}

Upvotes: 1

Related Questions