S_a_k_Uの日記みたいなDB

~サクゥーと呼ばないで~

setTimeoutの挙動、の続き

も少し突っ込んで、ボタンの割り込みなんかとの関係を確認。

<html>
<head></head>
<body>
  <input type="button" value="button" onclick="interruptEvent();" />
  <div id="stdout"></div>

<script>
var intcnt = 0;
var stdout = document.getElementById("stdout");

stdout.innerHTML += "<br>script start.<br>"

// waitのループ処理開始
setTimeout("waitEvent(0)", 200);

stdout.innerHTML += "<br>script end.<br>====<br>"

function interruptEvent() {
    intcnt++;
    stdout.innerHTML += "<br><span style='color:red'>[Event]button clicked.</span><br>"
     // 1,000[ms]待って割り込みメッセージを出力
    setTimeout( function() {
        stdout.innerHTML += "<b>interrupted</b>,"
    }, 1000 );
}

function waitEvent(n) {
    stdout.innerHTML += n + ","
    if (intcnt < 5) {
        // 200[ms]待ってカウントアップして次を出力(再帰)
        setTimeout("waitEvent(" + (n+1) + ")", 200);
    } else {
         // ボタンが5回クリックされたら終了
         // (最後に1,000[ms]待ってメッセージを出力)
           setTimeout( function() {
            stdout.innerHTML += "<br>end of waitEvent.<br>"
        }, 1000 );
    }
}
</script>

</body>
</html>
</script>

</body>
</html>
</script>

</body>
</html>

こんな結果に。

普通に待ち時間で直列に処理する仕組みっぽいな。