LoginSignup
11
10

More than 5 years have passed since last update.

setIntervalを連続使用すると、clearIntervalが効かない問題

Posted at

javascriptでゲームを作る際に毎秒を数え、制限時間を表示したかったのでsetIntervalを使用した。
だが、2度目の使用時にclearしたはずが前のintervalが残ってしまうことがあった。
どうやら他の人も直面したらしく、参考にさせていただいた。

http://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q1063499895

    var timerArray = new Array();
    function exec_interval() {
        timerArray.push(setInterval("alert('5秒間隔で表示されます。');", 5000));
    }

    function stop_interval() {
        if (timerArray.length > 0) {
        clearInterval(timerArray .shift());
        }
    }

shiftで配列にあるintervalを消すことで、全て綺麗に消えてくれた。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10