Skip to content

Instantly share code, notes, and snippets.

@alsotang
Last active October 15, 2015 07:25
Show Gist options
  • Save alsotang/a1fb0b791866c08aaa64 to your computer and use it in GitHub Desktop.
Save alsotang/a1fb0b791866c08aaa64 to your computer and use it in GitHub Desktop.
requestIdleCallback 与前端 cpu 运算
var count = 0;
setInterval(function () {
count++;
var el = document.querySelector('.count-number')
el.innerHTML = count;
}, 100)
// add 10k elements to body
setTimeout(function () {
for (var i = 0; i < 10000; i++) {
var div = document.createElement('div');
div.innerHTML = 0;
document.body.appendChild(div)
}
}, 2000)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<span class="count-number"></span>
<script type="text/javascript">
var count = 0;
setInterval(function () {
count++;
var el = document.querySelector('.count-number')
el.innerHTML = count;
}, 100)
// add 10k elements to body
setTimeout(function () {
var fragment = document.createDocumentFragment();
for (var i = 0; i < 10000; i++) {
var div = document.createElement('div');
div.innerHTML = 0;
fragment.appendChild(div)
}
document.body.appendChild(fragment)
}, 2000)
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<span class="count-number"></span>
<script type="text/javascript">
var count = 0;
setInterval(function () {
count++;
var el = document.querySelector('.count-number')
el.innerHTML = count;
}, 100)
// add 10k elements to body
setTimeout(function () {
var count = 0;
function draw() {
setTimeout(function () {
if (count < 10000) {
var div = document.createElement('div');
div.innerHTML = 0;
document.body.appendChild(div)
count++;
draw();
}
}, 0)
}
draw();
}, 2000)
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<span class="count-number"></span>
<script type="text/javascript">
var count = 0;
setInterval(function () {
count++;
var el = document.querySelector('.count-number')
el.innerHTML = count;
}, 100)
function ric(heavyWork, isDone, afterDone) {
afterDone = afterDone || function () {};
if (isDone()) {
afterDone();
return;
}
requestIdleCallback(function (deadline) {
while (deadline.timeRemaining() > 0 && !isDone()) {
heavyWork();
}
ric(heavyWork, isDone, afterDone);
});
}
// add 10k elements to body
setTimeout(function () {
var startTime = Date.now()
var count = 0;
ric(function () {
count++;
var div = document.createElement('div');
div.innerHTML = 0;
document.body.appendChild(div)
}, function () {
return count >= 10000
}, function () {
console.log(Date.now() - startTime)
})
}, 2000)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment