为什么setTimeout如此无效?
我有100个任务,每个任务需要1毫秒。我将它们与requestAnimationFrame交错,它应该在16ms左右。所以,我希望看到每个rAF执行这些任务中的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 :(得分:0)
根据bergi的评论和链接,setTimeout的限制为4毫秒
使用postMessage我每个rAF可以获得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);
}
&#13;