js基础编程-题目6

整理下初学时做过的js基础编程题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦

定时器

用setTimeout实现setInterval

这里需要用到递归,就是一个延时器走完了,要接上下一个延时器

function mySetInterval(fn,delay,timer=null){
    
    
  const interval =()=>{
    
    
    fn()
    timer = setTimeout(interval,delay)
  }
  setTimeout(interval,delay)
  return {
    
     //通过stop清楚定时器
    stop:()=>{
    
    
      clearTimeout(timer)
    }
  }
}

这里扩展下

  • 用定时器实现延时器
function mySetTimeout(fn,delay,timer=null){
    
    
  timer = setInterval(()=>{
    
    
    fn()
    clearInterval(timer)
  },delay)
}

猜你喜欢

转载自blog.csdn.net/hr_beginner/article/details/121262104