interval
# Node.js
let i = 0;
const id = setInterval(callback, 1e3);
function callback() {
console.log("called", i);
if (i === 3) {
clearInterval(id);
}
i++;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
Output
called 0
called 1
called 2
called 3
1
2
3
4
2
3
4
# Go
package main
import (
"fmt"
"time"
)
func callback(i int) {
fmt.Println("called", i)
}
func main() {
ticker := time.NewTicker(1 * time.Second)
i := 0
for range ticker.C {
callback(i)
if i == 3 {
ticker.Stop()
break
}
i++
}
}
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
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
Output
called 0
called 1
called 2
called 3
1
2
3
4
2
3
4
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22