LoginSignup
0
0

More than 5 years have passed since last update.

非同期処理をするsetTimeout関数を使って、コマンド引数から受け取った配列の要素を、一定時間ごとにコンソールに表示する関数を作る

Posted at

非同期処理で動く関数setTimeoutでハマり

特に使用場面があったわけではないのですが、記事タイトルの仕様をサクッと実装しようとしたらNode.js初心者的にはまったので自分用にメモ。


let index = 2; // process.argvが受け取る配列のうち、最初の二つは「node」と、「index.js」なので、3つ目から始める

function printByOneSecond(array) { // 受け取った配列の各要素を、1秒ごとにコンソールに表示する関数
    setTimeout(() =>{ // setTimeout(param1: 関数, param2: タイムアウトする時間)
        console.log(array[index]);
        index++;
        if (index < array.length) {
            printByOneSecond(array)
        }
    }, 1000);
}

printByOneSecond(process.argv);

実行結果

ezgif.com-video-to-gif.gif

0
0
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
0
0