JS (2M + 반복)에서 매우 긴 루프가 있습니다.
사용자에게 진행 상황을 보여주고 싶습니다.
어떤 이유로 코드가 중단되고 루프가 완료 될 때만 진행률이 표시됩니다.
내가 도대체 뭘 잘못하고있는 겁니까?
신중한 브라우저가 멈출 수 있으며 이에 따라 최대 설정
var MAX = 100000;
function doIt(){
alert('start count :'+ MAX);
for(i=0;i<MAX;i++){
setTimeout(updateBar, 600 , i);
console.log(i);
}
alert('count ended');
}
function updateBar(idx) {
var bar = document.getElementById('progress');
bar.style.width = Math.floor(100 * idx / MAX) + '%';
}
body {padding: 50px;}
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet"/>
<button onclick="doIt()">Start counting</button>
<div class="progress">
<div class="bar" id="progress"></div>
</div>
다음은 Web Worker를 사용하는 가능한 솔루션입니다 .
worker-script.js (고유 한 컨텍스트, 고유 한 파일)
// When this worker receives a message
self.addEventListener("message", onMessageReceive);
function onMessageReceive(e) {
// Get the max value
var max = e.data.value;
// Run the calculation
doIt(max);
}
function doIt(max) {
// Send messages to the parent from time to time
self.postMessage({ type: "start", value: max });
for (i = 0; i < max; i++) {
if (i % 5000 === 0) { // Every 5000 iterations - tweak this
self.postMessage({ type: "progress", value: i });
}
}
self.postMessage({ type: "end", value: max });
}
main.js (페이지 내)
var MAX = 20000000, // 20 millions, no problem
worker = null;
// If workers are supported, create one by passing it the script url
if (window.Worker) {
worker = new Worker("worker-script.js");
document
.getElementById("start-btn")
.addEventListener("click", startWorker);
} else {
alert("Workers are not supported in your browser.");
}
// To start the worker, send it the max value
function startWorker() {
worker.postMessage({ value: MAX });
}
// When the worker sends a message back
worker.addEventListener("message", onMessageReceive);
function onMessageReceive(e) {
var data = e.data;
switch (data.type) {
case "start":
console.log(`start count: ${data.value}`);
break;
case "progress":
updateBar(data.value);
break;
case "end":
updateBar(data.value);
console.log(`end count: ${data.value}`);
break;
}
}
function updateBar(idx) {
var bar = document.getElementById("progress");
bar.style.width = Math.floor((100 * idx) / MAX) + "%";
}
index.html
<button id="start-btn">Start counting</button>
<div class="progress">
<div class="bar" id="progress"></div>
</div>
<script src="main.js"></script>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다