使用setTimeout
实现setInterval
的最佳方法是什么?
考虑到被模拟的setInterval应该能够被“清除”。
发布于 2018-06-03 17:42:51
下面的代码使用setTimeout
创建了setInterval
的模拟实现
function interval(cb, ms){
var a = {
clear : function(){
clearTimeout(a.timer)
}
};
(function run(){
cb();
a.timer = setTimeout(run, ms);
})();
return a;
}
var myInterval_1 = interval(()=>{ console.log(1) }, 1000); // create an "interval"
var myInterval_2 = interval(()=>{ console.log(2) }, 1000); // create another "interval"
// clear the first interval
setTimeout(()=>{ myInterval_1.clear() }, 4000)
发布于 2018-06-04 03:03:42
为了准确地模拟setInterval,ons也必须模拟clearInterval:
{
const intervals = new Map();
function setInterval(fn, time, context, ...args) {
const id = Math.floor(Math.random() * 10000);
intervals.set(id, setTimeout(function next() {
intervals.set(id, setTimeout(next, time));
fn.apply(context, args);
}, time));
return id;
}
function clearInterval(id) {
clearTimeout(intervals.get(id));
}
}
您可以像往常一样使用它:
const interval = setInterval(console.log, 100, console, "hi");
clearInterval(interval);
发布于 2019-01-29 07:53:26
我有一个没有递归的基于promise的解决方案:)
function setInterval1(fn, time) {
let check = { check: true };
(async function () {
for (let i = 0; i < Number.POSITIVE_INFINITY && check.check; i++) {
await new Promise((resolve) => {
setTimeout(() => { fn(); resolve(true); }, time);
});
}
})();
return check;
}
let check = setInterval1(() => console.log('hi'), 1000);
function clearInterval1(check) {
check.check = false;
}
setTimeout(() => { clearInterval1(check) }, 4000)
https://stackoverflow.com/questions/50665051
复制相似问题