本文已参与「新人创作礼」活动,一起开启掘金创作之路。
源码
function Thread(config){
this.params = this.init(config);
}
Thread.prototype.init = function (config) {
const params = config ? config : {
start: function () {},
stop: function () {},
number: 0,
time: 300
};
params.start = params.start ? params.start : function (){};
params.stop = params.stop ? params.stop : function (){};
params.number = params.number ? Math.abs(parseInt(params.number)) : 0;
params.time = params.time ? Math.abs(parseInt(params.time)) : 300;
this.time = params.time
return params;
}
Thread.prototype.run = function () {
this.timer = setTimeout(this.runTime.bind(this), this.time)
}
Thread.prototype.runTime = function () {
try {
this.params.start()
} finally {
if (!this.params.number == 0) {
if (this.total >= this.params.number) {
this.params.stop()
clearTimeout(this.timer)
return
}
if (!this.total) {
this.total = 1
}
this.total++
}
clearTimeout(this.timer)
}
this.timer = setTimeout(this.runTime.bind(this), this.time)
}
Thread.prototype.stop = function () {
clearTimeout(this.timer)
this.params.stop()
}
使用示例一
const thread = new Thread({
start: function () {
console.log("轮询中...")
},
stop: function () {
console.log("轮询结束,结束方式:手动结束")
},
number: 0,
time: 1000
})
thread.run();
setTimeout(() => {
thread.stop()
}, 6000)
结果

使用示例二
const thread = new Thread({
start: function () {
console.log("轮询中...")
},
stop: function () {
console.log("轮询结束,结束方式:配置轮询次数")
},
number: 5,
time: 1000
})
thread.run();
结果

使用示例三
const thread = new Thread({
start: function () {
console.log("这里是轮询的回调")
},
number: 0,
time: 1000
})
thread.run();
结果
