zoukankan      html  css  js  c++  java
  • 防抖(debounce)和节流(throttle)

    防抖(debounce)

    当调用动作触发一段时间后,才会执行该动作,若在这段时间间隔内又调用此动作则将重新计算时间间隔

    function debounce(method, timeout, context) {
      return function() {
        var args = arguments
        clearTimeout(method.timer)
        method.timer = setTimeout(() => {
          method.apply(context, args)
        }, timeout)
      }
    }
    function handleResize() {
      console.log('resize')
    }
    window.onresize = debounce(handleResize, 500, window)

    节流(throttle)

    预先设定一个执行周期,当调用动作的时刻大于等于执行周期则执行该动作,然后进入下一个新的时间周期

    function throttle(method, timeout, context, cycle) {
      var startTime = +new Date()
      return function() {
        var args = arguments
        var currTime = +new Date()
        clearTimeout(method.timer)
        if (currTime - startTime >= cycle) {
          method.apply(context, args)
          startTime = currTime
        } else {
          method.timer = setTimeout(() => {
            method.apply(context, args)
          }, timeout)
        }
      }
    }
    function handleResize() {
      console.log('resize')
    }
    window.onresize = throttle(handleResize, 500, window, 2000)
  • 相关阅读:
    [编程题]多多的数字组合
    mac传输文件到服务器
    git 清除缓存、查看add内容
    go build
    vim编辑器
    Git: clone指定分支
    查看端口占用以及kill
    curl小记录
    Python3.9 malloc error: can’t allocate region
    设计模式-策略模式
  • 原文地址:https://www.cnblogs.com/zhoulixue/p/11106010.html
Copyright © 2011-2022 走看看