-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.js
More file actions
45 lines (37 loc) · 991 Bytes
/
timer.js
File metadata and controls
45 lines (37 loc) · 991 Bytes
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
// setTimeout最低延迟4ms
// 嵌套层数超过5层,默认设置4ms,如不超过,则默认设置1ms
// 不同浏览器最低延迟也不同
// 手写setTimeout
function setTimeout(fn, interval) {
let now = Date.now();
let bool = true;
while(bool) {
if(Date.now() - now >= interval) {
bool = true;
fn();
}
}
}
// 手写setInterval
function cSetInterval(fn, interval) {
// let timerId = null;
// let bool = false;
// const loop = () => {
// if (!bool) {
// fn();
// timerId = setTimeout(loop, interval);
// } else {
// bool = true;
// clearTimeout(timerId);
// }
// }
// timerId = setTimeout(loop, interval);
// return () => { bool = false };
cSetInterval.timer = setTimeout(() => {
fn();
cSetInterval(fn, interval);
}, interval);
}
function cClearInterval() {
clearTimeout(cSetInterval.timer);
}