throttling vs. debouncing

每天都在感叹前端水好深,每天都想爬上来写那么一点点。今天被说是卖萌/豆瓣风格的技术博客。I’ll take it as a compliment. 🙂

我跟老爷爷说jQuery有个功能叫debounce的时候他竟然”oh really?!”但是!他最后blahblah讲了应该怎样把keyup event传给setTimeout,然后补充说”which is basically how the debounce is implemented”的时候我断定他之前的惊讶是在唬我!( ̄工 ̄lll)

之前找到的几篇写得比较好的blog。

  • 关于throttling和debouncing的区别
    • Well, to put it simply: while throttling limits the execution of a function to no more than once every delay milliseconds, debouncing guarantees that the function will only ever be executed a single time (given a specified threshold).
  • Throttling example
    • Using jQuery throttle / debounce, you can pass a delay and function to $.throttle to get a new function, that when called repetitively, executes the original function (in the same context and with all arguments passed through) no more than once every delay milliseconds.
    • This can be especially useful for rate limiting execution of handlers on events like resize and scroll.
  • Debouncing example
    • Using jQuery throttle / debounce, you can pass a delay and function to $.debounce to get a new function, that when called repetitively, executes the original function just once per “bunch” of calls.
    • This can be especially useful for rate limiting execution of handlers on events that will trigger AJAX requests.
  • Implementations
    • 简单来说
      • throttle calls to “callback” routine and ensure that it is not invoked any more often than “delay” milliseconds. if “delay” milliseconds have expired since the previous call then propagate this call to “callback”
      • debounce calls to “callback” routine so that multiple calls made to the event handler before the expiration of “delay” are coalesced into a single call to “callback”. Also causes the wait period to be reset upon receipt of a call to the debounced routine. if a timeout has been registered before then cancel it so that we can setup a fresh timeout

1 thought on “throttling vs. debouncing”

Leave a reply to Everything about DOM | My Blueberry Nights Cancel reply