JavaScriptでシンプルなタイマーのサンプル。
JavaScriptで一定時間ごとに処理を実行するための、シンプルなタイマーのサンプルです。
| 
					 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  | 
						function setTimer(callback, time) { 	let id = window.setInterval(play, time); 	let timer, time_start, time_rest; 	timer = { 		reset:() => { 			window.clearInterval(id); 			time_rest = 0; 		}, 		pause:() => { 			window.clearInterval(id); 			time_rest = time-(new Date()-time_start); 		}, 		resume:() => { 			window.clearInterval(id); 			window.setTimeout(() => { 				id = window.setInterval(play, time); 			}, time_rest); 		}, 	}; 	return timer; 	function play() { 		time_start = new Date(); 		callback(); 	} }  | 
					
使い方は「setTimmer」オブジェクトを作成して、引数に実行したい関数と時間を設定します。
| 
					 1 2 3 4 5  | 
						function test() {   console.log("テスト"); } let timmer = setTimer(test, 5000);  | 
					
上記では5秒ごとに、コンソールログに「テスト」と出力されます。
タイマーの一時停止には「pause()」、経過時間のリセットには「reset()」、再開には「resume()」を実行します。
| 
					 1 2 3  | 
						timmer.reset(); timmer.pause(); timmer.resume();  |