2 Star 1 Fork 0

黎明就在前方 / SetInterval

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
interval.js 1.51 KB
一键复制 编辑 原始数据 按行查看 历史
黎明就在前方 提交于 2022-09-29 09:03 . update interval.js.
/***
* 此js文件中的构造函数、方法用于修复异常api:::
*
* SetInterval Function构造函数 修复setInterval每次定时执行的偏差,适用于倒计时场景
* 用法:
* var test = new SetInterval(callback, 1000); //开始定义倒计时
* test.$clear(); // 移除
*/
//修复setInterval每次定时执行的偏差,适用于倒计时场景
/**
* callback: 每次回调执行函数
* time: 每隔多少时间回调一次
*/
function SetInterval(callback, time) {
this.start = new Date().getTime();
this.end;
this.offset;
this.loopNum = 0;
this.timeoutTag = null;
this.time = time;
this.callback = callback;
this.$set(time);
}
SetInterval.prototype.$set = function (_time) {
var that = this;
if (this.timeoutTag === undefined) return;
clearTimeout(this.timeoutTag);
this.timeoutTag = null;
that.timeoutTag = setTimeout(function () {
that.loopNum++;
that.end = new Date().getTime();
that.callback();
that.offset = that.end - that.start - that.time * that.loopNum;
//console.log("333,,,偏移了" + that.offset);
if (that.offset > 0) {
that.$set(that.time - that.offset);
} else if (that.offset < 0) {
that.$set(that.time + that.offset);
} else {
that.$set(that.time);
}
}, _time);
};
SetInterval.prototype.$clear = function () {
clearTimeout(this.timeoutTag);
//便于拦截区分,此处必须设置为undefined
this.timeoutTag = undefined;
};
export {
SetInterval
}
1
https://gitee.com/dmui/set-interval.git
git@gitee.com:dmui/set-interval.git
dmui
set-interval
SetInterval
master

搜索帮助