Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
2.01k stars 236 forks source link

使用 setTimeout 实现 setInterval #156

Open Sunny-117 opened 2 years ago

CwRv07 commented 1 year ago
function _setInterval(fn,delay=4,...args) {
  let cancel = false;
  const task = () => {
    setTimeout(() => {
      if (!cancel) {
        fn.apply(this, args);
        task();
      }
    },delay)
  }
  task();
  return () => { cancel = true };
}
hyxieshi commented 1 year ago

function interval(callback, time) { let inter = () => { setTimeout(() => { callback(); inter(); }, time); }; inter(); } interval(() => { console.log(每隔1秒输出); }, 1000);

LifeIsTerrible commented 1 year ago

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)
nanyishixiong commented 1 year ago
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)
2239351258 commented 1 year ago
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)
})()
cscty commented 1 year ago

function interval(fn, delay = 0, ...args) { setTimeout(() => { fn(...args); interval(fn, delay, ...args); }, delay); }

IhInspiration commented 1 year ago
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)
jianxingyao commented 1 month ago
function mySetInterval(cb,time){
    setTimeout(() => {
        cb()
        mySetInterval(cb,time)
    },time)
}
mySetInterval(() => {
    console.log('hello')
},1000)