zashii-1434

Stats of My Life(おいしい人生を味わうために、コツコツとチャレンジしたことを書くブログ)

JavaScript-setTimeoutとsetInterval

備忘

 

setTimeoutはミリ秒後に関数を1回呼び出す

setTimeoutはミリ秒後に関数を繰り返し呼び出す

 

 

<!DOCTYPE html>
<html>
<head>
 
<script>
var timerId;
 
function timeoutStart(){
//タイマーの開始
timerId = setTimeout(whattime, 3000);
}

function timeoutStop(){
clearTimeout(timerId);
}

function intervalStart() {
clearInterval(timerId);
timerId = setInterval(whattime, 2000);
}
function intervalStop() {
cleartInterval(timerId);
}

function whattime() {

document.getElementById("info").textContent = new Date();

}

</script>
</head>
<body>
<button onclick="timeoutStart()">setTimeout</button>
<button onclick="timeoutStop()">clearTimeout</button>
<button onclick="intervalStart()">setInterval</button>
<button onclick="intervalStop()">clearInterval</button>

<p id="info"></p>
</body>
</html>