JavaScript setTimeoutメソッドで一定時間の経過後に実行するサンプル

環境
Google Chrome 106.0.5249.91
Windows 10 Home 64bit

構文
変数 = setTimeout(関数名,ミリ秒 [,引数…])
指定したミリ秒の経過後、関数が1度実行されます。1000ミリ秒は、1秒です。
3つめ以降の引数は、1つめの関数に渡す引数を指定できます。
setTimeoutメソッドの戻り値は、タイマーを識別する数値を返します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<input type="button" value="開始" onclick="startFun()" />
<p><input type="button" value="停止" onclick="endFun()" /></p>
<script>
let timerA;
//開始処理関数
function startFun() {
if(timerA){
endFun();
}
// 開始ボタンを押すと2秒ごとに文字列が出力される
timerA = setInterval(procA, 2000);
}
//関数procA
procA = function () {
console.log("2秒経過しました");
};
//終了処理関数
function endFun() {
// setIntervalメソッドで開始された処理を停止
clearInterval(timerA);
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <input type="button" value="開始" onclick="startFun()" /> <p><input type="button" value="停止" onclick="endFun()" /></p> <script> let timerA; //開始処理関数 function startFun() { if(timerA){ endFun(); } // 開始ボタンを押すと2秒ごとに文字列が出力される timerA = setInterval(procA, 2000); } //関数procA procA = function () { console.log("2秒経過しました"); }; //終了処理関数 function endFun() { // setIntervalメソッドで開始された処理を停止 clearInterval(timerA); } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<input type="button" value="開始" onclick="startFun()" />
<p><input type="button" value="停止" onclick="endFun()" /></p>

<script>
  let timerA;
  //開始処理関数
  function startFun() {
    if(timerA){
      endFun();
    }
    // 開始ボタンを押すと2秒ごとに文字列が出力される
    timerA = setInterval(procA, 2000);
  }
  //関数procA
  procA = function () {
    console.log("2秒経過しました");
  };
  //終了処理関数
  function endFun() {
   // setIntervalメソッドで開始された処理を停止
    clearInterval(timerA);
  }
</script>

</body>
</html>

実行結果
開始ボタンを押すと2秒ごとに文字列が出力されます。
停止ボタンを押すと定期処理が停止します。

JavaScript

Posted by arkgame