js实现 throttle 和 debounce

 debounce (fn, delay) {
    delay = delay || 600
    let timer
    return function () {
      let ctx = this
      let args = arguments
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        timer = null
        fn.apply(ctx, args)
      }, delay)
    }
  },
  throttle (fn, interval) {
    let last
    let timer
    interval = interval || 600
    return function () {
      let ctx = this
      let args = arguments
      let now = new Date()
      if (last && now - last < interval) {
        clearTimeout(timer)
        timer = setTimeout(function () {
          last = now
          fn.apply(ctx, args)
        }, interval)
      } else {
        last = now
        fn.apply(ctx, args)
      }
    }
  }
posted @ 2020-03-19 11:37  缥缈飞云  阅读(448)  评论(0编辑  收藏  举报