需求:在进入页面时,开始循环倒计时,每当倒计时一轮完成后,发送请求自动保存数据。

有一点较麻烦的是setInterval会有延迟时间,在进入页面后不会立即执行一次,而是先等一次设置的delay过了,才会开始循环,要做到立即执行,需要做相应的处理,我这里用的是通过function()来立即执行,再在函数中返回本身来达到立即执行再开始循环的方法(还有其他方法可自行搜索)。

立即执行setInterval:

// 立即执行setInterval定时器:这里注意改变一下this的指向,把指向vue实例的this传进去,不然this为undefined,返回本身的时候也是同理

let func = function tempFun() {
        console.log("enter sentInterval");
        return tempFun.bind(this);
}.bind(this);

setInterval(func(), 3000);

整体代码如下:

data() {
    return {
      // 页面显示倒计时的数字
      count: 10,
    };
  },

mounted() {
   // 页面初始化调用
   this.repeatCountDown();
  },

methods: {
    // 倒计时
    countDown() {
      // 有定时器 -> 清除定时器(避免重复设置)
      if (window.timer) {
        clearInterval(window.timer);
      }
      // 设置定时器
      window.timer = setInterval(() => {
        if (this.count > 0) {
          this.count--;
          if (this.count == 0) {
            // 倒计时到0时发送请求 并清除定时器
            // do something
            console.log("send req");
            clearInterval(window.timer);
         }
       }
      }, 1000);
    },

    // 循环倒计时
    repeatCountDown() {
      let func = function tempFun() {
        this.count = 10;
        this.countDown();
        return tempFun.bind(this);
      }.bind(this);
      setInterval(func(), 11000);  // delay要比倒计时的数字大1,因为要倒计时到0
    },
  },

Logo

前往低代码交流专区

更多推荐