js实现在一段时间内, 经过指定的时间调用指定的方法

 let init = function (time, interval, func) {
       let timeObj = {
           time,
           interval,
           func,
           intervalId: window.undefined,
           curTime: window.undefined,
           curTimeIntervalId: window.undefined,
           bindFunc: function (obj, func) {
             return function () {
                func.apply(obj);
             }  
           },
           curTimmFunc: function () {
               if (this.curTime < 1){
                    window.clearInterval(this.curTimeIntervalId);
                    return;
               }
               if (this.curTime > 0){
                   this.curTime = this.curTime - 1;
               }
           },
           start: function () {
               this.curTime = time;
               let fun1 = this.bindFunc(this, this.intervalFunc);
               let fun2 = this.bindFunc(this, this.curTimmFunc);
               this.intervalId = window.setInterval(fun1, interval * 1000);
               this.curTimeIntervalId = window.setInterval(fun2, 1000)
           },
           intervalFunc: function () {
                if (this.curTime < 1){
                    window.clearInterval(this.intervalId);
                    window.clearInterval(this.curTimeIntervalId);
                    return;
                }
                this.func()
           }
       }
       let result = {
            get curTime() {
                return timeObj.curTime
            },
            start: function () {
                timeObj.start();
            }
       }
       return result;
   }

   // 20 秒内每过 5 秒执行一次
   this.timer = init(20, 5, function () {
       console.log(2222);
   })
 
 // 开始
   this.timer.start();
posted @ 2020-03-26 18:35  xiaoxiaobiao  阅读(571)  评论(0)    收藏  举报