-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
使用 setTimeout 实现 setInterval #156
Comments
function _setInterval(fn,delay=4,...args) {
let cancel = false;
const task = () => {
setTimeout(() => {
if (!cancel) {
fn.apply(this, args);
task();
}
},delay)
}
task();
return () => { cancel = true };
} |
function interval(callback, time) { |
|
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) { |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: