<!-- 模拟执行 --> <!-- let ms = 2000; let asyncMs = 1000; var set = new setIntervalWaitable(()=>{ setTimeout(function(){ set.request() }, asyncMs) }, ms) set.request() -->
function setIntervalWaitable2(callback,ms){ this._self = { fn: callback, timeout: ms, timeoutHandler: null, start: null, duration: null } } setIntervalWaitable2.prototype.request = function() { let that = this; let timeout = 0; //首次直接执行事件
if (that._self.timeoutHandler) { clearTimeout(that._self.timeoutHandler); } // 判断 if (that._self.start) { //计算更新timeout值 that._self.duration = new Date().getTime() - that._self.start; if (that._self.duration < that._self.timeout) { timeout = that._self.timeout - that._self.duration; } } that._self.timeoutHandler = setTimeout(() => { that._self.start = new Date().getTime(); that._self.fn(); }, timeout); }
<!-- 模拟执行 let ms = 2000; let asyncMs = 1000; //假设异步操作时间
var set = new setIntervalWaitable2(()=>{ setTimeout(function(){ console.log('函数执行' + new Date().getSeconds()) set.request() }, asyncMs) }, ms) set.request() -->
<!-- 模拟执行 --> <!-- let ms = 2000; let asyncMs = 1000; //假设异步操作时间
var set = new setIntervalWaitable3(()=>{ setTimeout(function(){ console.log('函数执行' + new Date().getSeconds()) set.request() }, asyncMs) }, ms) set.request() //执行 -->