开发者

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";


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(/* ... */);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜