0
0

More than 1 year has passed since last update.

Node.js: タイマーの使い方

Last updated at Posted at 2022-10-03

こちらのページを参考にしました。
Node.jsでsetTimeoutを使ったタイマー

ライブラリーのインストール

sudo npm install -g date-utils
timer_test.js
#! /usr/local/bin/node
// ---------------------------------------------------------------
//	timer_test.js
//
//					Oct/3/2022
// ---------------------------------------------------------------
'use strict'
require('date-utils')

var count = 0
function counter () {
    var dt = new Date()
    var formatted = dt.toFormat("HH24:MI:SS")
    console.log(count++, "只今の時刻:",formatted)
    const timeoutId = setTimeout(counter, 2000)

	if (count == 5)
		{
		clearTimeout(timeoutId)
		console.error ("*** 終了 ***")
		}
}

// ---------------------------------------------------------------
console.error ("*** 開始 ***")
counter()
// ---------------------------------------------------------------

実行スクリプト

start.sh
export NODE_PATH=/usr/local/lib/node_modules
./timer_test.js

実行結果

$ ./start.sh 
*** 開始 ***
0 只今の時刻: 20:00:15
1 只今の時刻: 20:00:17
2 只今の時刻: 20:00:19
3 只今の時刻: 20:00:21
4 只今の時刻: 20:00:23
*** 終了 ***

次のバージョンで確認しました。

$ node --version
v19.6.0
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