js 定时器

需求:10秒内请求一次服务器,数据达到想要的效果后,清除定时器。

下面是效果图

 

 下面是实现代码

  <div class="footer">
       <el-button :loading="subloading" type="primary" style="width:220px;" 
          @click="initData">{{ $t('tagsView.refresh') }}<span v-show="count >0">({{ 
          count  }})</span>
      </el-button>
  </div>


data() {
    return {
      timer: null,
      count: 0,
      subloading: false,
      form: {
        info: undefined,
        stime: undefined,
        etime: undefined,
        tagNum: 0,
        clasNum: 0,
        itemNum: 0,
        isRun: false,
        sync: false,
        subject: false,
        cartoon: false,
        knowledge: false
      }
    }


  created() {
    clearInterval(this.timer)  //为避免初始化完成后定时器存在,先清除
    this.initData()
  },

 beforeDestroy() { // Vue 页面销毁前启动此函数 如页面突然被关闭
    clearInterval(this.timer)
    this.count = 0
  },

methods:{
    initData() { //向服务器请求函数
      clearInterval(this.timer)//执行前先清除 避免创建多个定时器 避免潜在bug
      this.form_loading = true
      this.subloading = true
      this.urlmethod(this.url.gery.log, null).then(res => {
        this.form.info = res.data.info
        this.form.stime = res.data.stime
        this.form.etime = res.data.etime
        this.form.tagNum = res.data.tagNum
        this.form.clasNum = res.data.clasNum
        this.form.itemNum = res.data.itemNum
        this.form.isRun = res.data.isRun
        if (!res.data.isRun) {
          clearInterval(this.timer)
          this.count = 0
        } else {
          this.countDown(10)
        }
        this.form_loading = false
        this.subloading = false
      }).catch(() => {
        clearInterval(this.timer)
        this.form_loading = false
        this.subloading = false
      })
    },
}

//定时计数器 计数到10即请求服务
 countDown(count) {
      this.count = count
      this.timer = setInterval(() => {
        if (this.count > 0 && this.count <= count) {
          --this.count
        } else {
          this.count = 10
          this.initData()
        }
      }, 1000)
    }


版权声明:本文为u012174809原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。