<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script data-require="bootstrap@*" data-semver="3.3.6" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>單一執行緒的 javascript</h1>
<div>
執行一個時間很長的工作,由於單一執行緒,所以畫面與按鈕的事件不會被觸發。(請小心使用...)<br />
<button id="btnLoop" class="btn btn-default">長時間事件</button><br/>
將一個很長時間的工作切割,透過 setTimeout 一個接著一個的呼叫,讓畫面與按鈕事件還是可以觸發。<br />
<button id="btnSplitLoop" class="btn btn-default">大量短時間事件</button>
<br />
<button class="btn btn-default" onclick="alert('Btn Event')">觸發測試事件</button><br />
<table id="output">
</table>
</div>
</body>
</html>
// Add your javascript here
$(function(){
$("#btnLoop").on("click", function(){
$("#output").html('')
var table = document.getElementById("output");
for(var i = 0 ; i < 200000 ; i++){
var tr = document.createElement("tr");
for(var t = 0 ; t < 6 ;t++){
var td = document.createElement("td");
td.appendChild(document.createTextNode(i+","+t));
tr.appendChild(td)
}
table.appendChild(tr);
}
})
$("#btnSplitLoop").on("click", function(){
var jobs = 200000;
var divideInto = 2000;
var perSize = jobs/divideInto;
var iter = 0;
var timeout = 10;
var table = document.getElementById("output");
setTimeout(function genRows(){
$("#output").html('')
var base = perSize * iter;
for(var i = 0 ; i < perSize ; i++){
var tr = document.createElement("tr");
for(var t = 0 ; t < 6 ;t++){
var td = document.createElement("td");
td.appendChild(document.createTextNode((i+base)+","+t+","+iter+"&ensp"));
tr.appendChild(td)
}
table.appendChild(tr);
}
iter++;
if(iter < divideInto){
setTimeout(genRows, 0);
}
}, 0);
})
});
/* Put your css in here */