-
Notifications
You must be signed in to change notification settings - Fork 4
/
timeSlicing.html
49 lines (46 loc) · 1.05 KB
/
timeSlicing.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>时间切片</title>
</head>
<body>
<p>把长任务切割成多个小任务</p>
<script>
function ts (gen) {
if (typeof gen === 'function') gen = gen()
if (!gen || typeof gen.next !== 'function') return
(function next () {
const res = gen.next()
if (res.done) return
setTimeout(next)
})()
}
// 改进版
function ts1 (gen) {
if(typeof gen === 'function') gen = gen()
if(!gen || typeof gen.next !== 'function') return
(function next() {
const start = performance.now()
let res = null
do {
res = gen.next()
} while(!res.done && performance.now() - start < 25)
if (res.done) return
setTimeout(next)
})()
}
/*
* @test
*/
ts1(function* () {
const start = performance.now()
while (performance.now() - start < 1000) {
console.log(11)
yield
}
console.log('done!')
});
</script>
</body>
</html>