Vue项目中定时器动态修改时间间隔

<script>
export default {
  name: "IndexVue",
  data() {
    return {
      // 定时器标识
      mySetInterval:"",
      // 定时任务序列
      sequence:[
        {n:1,time:300,options:{}},
        {n:2,time:300,options:{}},
        {n:3,time:300,options:{}},
        {n:4,time:300,options:{}},
      ]
  },
  methods: {
  // 开启定时器
    openMySetInterval(callback){
      this.mySetInterval =setInterval(
        this.mySetIntervalCallback,0,callback
      );
    },
    // 定时器回调函数
    mySetIntervalCallback(callback,options=""){
      if (this.sequence.length > 0) {
         // 复制一份数据
         let n = this.sequence[0].n ;
         let time = this.sequence[0].time;
         let options = this.sequence[0].options;
         // 删除第一个元素
         this.sequence.shift();
         // 销毁定时器重新赋值
         clearInterval(this.mySetInterval);
         this.mySetInterval =setInterval(
           this.mySetIntervalCallback,
           time,callback,options
         );
      }else{
        // 销毁定时器
        clearInterval(this.mySetInterval);
       // 执行定时器结束的回调
       callback();
      }
    }
  }
}
</script>
This entry was posted in js, Vue. Bookmark the permalink.

发表回复