-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetInterval.html
More file actions
64 lines (53 loc) · 1.52 KB
/
setInterval.html
File metadata and controls
64 lines (53 loc) · 1.52 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// Method1
let timeMap = {}
let id = 0
function mySetInterval(foo, timeout) {
let timeID = id
id++
const fn = () => {
foo()
timeMap[timeID] = setTimeout(() => { fn() }, timeout)
}
timeMap[timeID] = setTimeout(fn, timeout)
return timeID
}
function myClearTimeout(timeID) {
clearTimeout(timeMap[timeID])
delete timeMap[timeID]
}
// Method2
// function mySetInterval(foo, timeout) {
// var timer = {
// id: null
// }
// function fn() {
// foo();
// timer.id = setTimeout( ()=> {
// fn();
// }, timeout);
// }
// fn();
// return timer
// }
// function myClearTimeout(timer) {
// clearTimeout(timer.id);
// }
const newTime = mySetInterval(() => { // 此处id是Number类型,是值的拷贝而不是引用
console.log(new Date())
}, 1000)
setTimeout(() => { // 2秒后清除定时器
myClearTimeout(newTime)
}, 5000)
</script>
</body>
</html>