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

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

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

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

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

Example

clearInterval()

var myVar = setInterval(() => {
  myTimer()
}, 1000)

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

function myStopFunction() {
  clearInterval(myVar)
}

clearTimeout()

var myVar

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

function myStopFunction() {
  clearTimeout(myVar)
}

用vue實做

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

參考資料