2016-04-15 86 views
0

爲什麼setTimeout如此無效?setTimeout爲什麼非高效

我有100個任務應該每個1ms。我將它們與requestAnimationFrame交錯,應該在16ms左右。所以,我期望看到14-16這些任務爲每個RAF執行。相反,我認爲每場比賽1-3次。

var count = 0; 
 
var limit = 100; 
 

 
function doSomething1ms() { 
 
    var start = performance.now(); 
 
    while (performance.now() - start < 1); 
 
    log("finished: " + count); 
 
    if (++count < limit) { 
 
    setTimeout(doSomething1ms, 0); 
 
    } 
 
} 
 
doSomething1ms(); 
 
    
 
var rafCount = 100; 
 
function raf() { 
 
    log("raf"); 
 
    --rafCount; 
 
    if (rafCount) { 
 
    requestAnimationFrame(raf); 
 
    } 
 
}; 
 
requestAnimationFrame(raf); 
 

 
log("start------------------------"); 
 

 
function log(msg) { 
 
    var div = document.createElement('div'); 
 
    div.appendChild(document.createTextNode(msg)); 
 
    document.body.appendChild(div); 
 
}

+0

看看[在這種情況下爲什麼native承諾似乎比chrome中的回調更快](http://stackoverflow.com/a/22759890/1048572) – Bergi

+0

不幸的是承諾不會通過事件隊列如果我使用鏈式承諾raf不執行 – gman

+0

是的,但嘗試鏈接那裏的其他技術,如'postMessage'或'setImmediate' – Bergi

回答

0

基於BERGI的評論和鏈接的setTimeout有4ms的

使用的postMessage我得到每RAF哪個更好雖然仍遠遠短16

7-10呼叫限制

var count = 0; 
 
var limit = 100; 
 

 
function doSomething1ms() { 
 
    var start = performance.now(); 
 
    while (performance.now() - start < 1); 
 
    log("finished: " + count); 
 
    queueNext(); 
 
} 
 

 
window.addEventListener('message', doSomething1ms); 
 

 
function queueNext() { 
 
    if (++count < limit) { 
 
    window.postMessage({}, "*", []); 
 
    } 
 
} 
 
queueNext(); 
 
    
 
var rafCount = 100; 
 
function raf() { 
 
    log("raf"); 
 
    --rafCount; 
 
    if (rafCount) { 
 
    requestAnimationFrame(raf); 
 
    } 
 
}; 
 
requestAnimationFrame(raf); 
 

 
log("start------------------------"); 
 

 
function log(msg) { 
 
    var div = document.createElement('div'); 
 
    div.appendChild(document.createTextNode(msg)); 
 
    document.body.appendChild(div); 
 
}