Skip to content

Instantly share code, notes, and snippets.

@riskers
Last active October 19, 2022 09:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save riskers/e3f4369cb2bc6321170410bdde009bbb to your computer and use it in GitHub Desktop.
throttle and debounce
  • throttle 定义了一个函数一段时间内的最多执行次数,比如『执行这个函数最多每100ms执行一次』
  • debounce 定义了一个函数在一定时间过去也没有被调用。比如『执行这个函数在没有被调用的100ms之后』

var throttle = function(fn, delay){
    var last = 0

    return function() {
        var now = +new Date(),
            context = this,
            args = arguments

        if(now - last > delay){
            last = now
            fn.apply(context, args)
        }
    }
}

var debounce = function(fn, delay){
    var timeId = null

    return function(){
        var context = this,
            args = arguments

        clearTimeout(timeId)

        timeId = setTimeout(function(){
            fn.apply(context, args)
        }, delay)
    }
}
// demo
window.onresize = _.throttle(function(){
  console.log(1)
},1000)
window.onresize = _.debounce(function(){
  console.log(1)
},1000)

window.onresize = throttle(function() {
  console.log(1)
}, 1000)
// 传值
var callback = debounce(function(xx){
    console.log(xx)
}, 1000)

window.onresize = function() {
    callback('value')
}
  • throttle 是在 onresize 事件中每隔 delay 就会发生一次 console
  • debounce 是在停止 onresize 事件后隔 delay 发生一次 console
@riskers
Copy link
Author

riskers commented Sep 29, 2016

@riskers
Copy link
Author

riskers commented Jan 11, 2019

@riskers
Copy link
Author

riskers commented Sep 24, 2020

application in React

重点是把同步的和要 debounce/throttle 的异步函数分开,并且在 constructor 阶段就把 debounce/throttle 部分做好。

import debounce from 'lodash/debounce'

class T extends React.Component {
  constructor(props) {
    super(props)
    this.debounceOnChange = debounce(this.deOnChange, 300)
  }
                                 
  onChange = (e) => {
    e.persist()
    /**
     * something sync:
     *
     *  this.setState({
     *
     *  })
    **/
    
    // something async:
    this.debounceOnChange(e)
  }

  debounceOnChange = (e) => {
    //fetch(...)
  }
  
  render() {
    return(
      <input onChange={this.onChange} />
    )
  }
}

@riskers
Copy link
Author

riskers commented Oct 19, 2022

React Hooks 中使用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment