Vue.js中使用setInterval、clearInterval、clearLnterval、setTimeout

前些日子在做FreeCodeCamp的題目「Build a Pomodoro Clock」需要做計數功能,但是大部分使用setTimeout的範例都是JQuery版本,因此在此做個紀錄。

方法 描述
setInterval 定期去調用function或者執行一段程式。
clearInterval 取消掉setInterval所重複執行的動作。
setTimeout 在指定的延遲時間之後調用一個函數或者執行一段程式。
clearTimeout 可取消由 setTimeout() 設置的 timeout。

Example

clearInterval()

1
2
3
4
5
6
7
8
9
10
11
12
13
var myVar = setInterval(() => {
myTimer()
}, 1000)

function myTimer() {
var d = new Date()
var t = d.toLocaleTimeString()
console.log(t)
}

function myStopFunction() {
clearInterval(myVar)
}

clearTimeout()

1
2
3
4
5
6
7
8
9
10
11
var myVar

function myFunction() {
myVar = setTimeout(() => {
console.log('Hello')
}, 3000)
}

function myStopFunction() {
clearTimeout(myVar)
}

用vue實做

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let vm = new Vue({
el: '#app',
data: {
time: null,
},
methods: {
timer() {
let my = this
this.time = setInterval(() => {
// do something...
}, 1000)
},
setTime() {
this.timer()
},
stopTime() {
if (this.time) {
clearInterval(this.time)
}
}
}
})

Demo

Build a Pomodoro Clock
Codepen: Build a Pomodoro Clock

參考資料