在vue項目中使用輪詢器《輪詢》

<template>
  <div>
    {{text}}
  </div>
</template>

<script>
export default {
  props: {

  },
  data () {
    return {
      text: 0,
      timerId: 1, // 模擬計時器id,唯一性
      timerObj: {} // 計時器存儲器
    }
  },
  computed: {

  },
  created () {
    this.startTraining()
  },
  destroyed () {
    this.stopTime()
  },
  mounted () {

  },
  watch: {

  },
  methods: {
    // 開始輪訓
    startTraining () {
      let that = this
      const id = this.timerId++
      this.timerObj[id] = true

      async function timerFn () {
        if (!that.timerObj[id]) return
        await that.doSomething()
        setTimeout(timerFn, 3 * 1000)
      }

      timerFn()
    },
    // 停止輪訓
    stopTime () {
      this.timerObj = {}
    },
    // 需要輪訓的事件
    doSomething () {
      this.testing()
    },
    testing () {
      this.text += 1
    }

  },
  components: {

  }
}
</script>

<style lang="scss" scoped>
</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章