LoginSignup
2
5

More than 5 years have passed since last update.

JavaScriptでループ中にスリープする。

Last updated at Posted at 2017-04-22

この記事は、
JavaScriptでループ中にスリープしたい。それも読みやすいコードで
を見て、改良してみたものです。

ループ中の i が 0 から、ループ数、だと、
Forのように、start から end までを定義できたほうがいいなと思ったので
次のようなものを作りました。

function intervalForTo(startIndex,endIndex, interval, func) {
    if (!(startIndex <= endIndex)) { return; }
    var i = startIndex;
    var loopFunc = function () {
        if ( func(i) === false) {
            //戻り値がfalseならループをbreakする
            return;
        }
        if (i < endIndex) {
            setTimeout(loopFunc, interval);
        }
        i++;
    }
    loopFunc();
}

function intervalForDownTo(startIndex,endIndex, interval, func) {
    if (!(endIndex <= startIndex)) { return; }
    var i = startIndex;
    var loopFunc = function () {
        if ( func(i) === false) {
            //戻り値がfalseならループをbreakする
            return;
        }
        if (endIndex < i) {
            setTimeout(loopFunc, interval);
        }
        i--;
    }
    loopFunc();
}

使い方は、次のようにします。

    intervalForTo(5, 10, 500, function(index) {
        alert(index.toString());
    });
    //5,6,7,8,9,10 と表示されます。

    intervalForDownTo(10, 5, 500, function(index) {
        alert(index.toString());
    });
    //10,9,8,7,6,5 と表示されます。

intervalForTo / intervalForDownTo で囲まれている部分にたいして
return true; で、continue
return false;で、break の機能があります。

setTimeout で実装していますが

元記事のコメント欄にあった、
setInterval を使った実装もしてみましたので、

より詳しい内容は、GitHubの方をどうぞ

standard-software/stsLib.js/stslib_web.js

2
5
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
2
5