Open Sunny-117 opened 2 years ago
function interval(callback, time) {
let inter = () => {
setTimeout(() => {
callback();
inter();
}, time);
};
inter();
}
interval(() => {
console.log(每隔1秒输出
);
}, 1000);
let timer = null;
function myInterval(cb, delay) {
let interval = () => {
cb();
timer = setTimeout(interval, delay); // 递归执行
}
timer = setTimeout(interval, delay); //触发执行
}
myInterval(() => { console.log('I am Jack') }, 1000)
function mySetInterval(func, delay, ...args) {
let timer = null
function fun() {
return setTimeout(() => {
func(...args)
timer = fun()
}, delay)
}
timer = fun()
return () => { clearTimeout(timer) }
}
let clear = mySetInterval(() => {
console.log(11);
}, 1000)
setTimeout(() => {
clear()
}, 2100)
let timeWorker = {}
let _setInterval = function (fn, time,...args) {
// 定义一个key,来标识此定时器
let key = Symbol();
// 定义一个递归函数,持续调用定时器
let execute = function (fn, time) {
timeWorker[key] = setTimeout(function () {
fn(...args);
execute(fn, time);
}, time)
}
execute(fn, time);
// 返回key
return key;
}
let _clearInterval = function (key) {
if (key in timeWorker) {
clearTimeout(timeWorker[key]);
delete timeWorker[key];
}
}
// test
!(() => {
let timer = _setInterval(() => console.log(1), 1000)
setTimeout(() => {
_clearInterval(timer)
}, 10000)
})()
function interval(fn, delay = 0, ...args) { setTimeout(() => { fn(...args); interval(fn, delay, ...args); }, delay); }
function mySetInterval(fn, delay, ...args) {
let timer = null;
const task = () => {
timer = setTimeout(() => {
if (timer) {
fn.apply(this, args);
task();
}
}, delay);
}
task();
return () => {
clearTimeout(timer);
timer = null;
}
}
const cancel = mySetInterval(console.log, 1000, 'mySetInterval')
setTimeout(() => {
cancel();
}, 4500)
function mySetInterval(cb,time){
setTimeout(() => {
cb()
mySetInterval(cb,time)
},time)
}
mySetInterval(() => {
console.log('hello')
},1000)