Putting debounce and throttle together can be very confusing, because they both share a parameter called delay
.

Debounce. The delay
is to wait till there's no more invokes anymore, then to invoke it. Very much like to close an elevator door: the door has to wait till no one tries to get in before closing.
Throttle. The delay
is to wait with a frequency, then invokes for the last one. Very much like to fire a pistol gun, the gun just can't be fired beyond certain rate.
Let's take a look at the implementation to see in details.
function debounce(fn, delay) {
let handle = null
return function () {
if (handle) {
handle = clearTimeout(handle)
}
handle = setTimeout(() => {
fn(...arguments)
}, delay)
}
}
Debounce, keeps interrupting the timeout until no more interruptions, and then fires fn
.
function throttle(fn, delay) {
let handle = null
let prevArgs = undefined
return function() {
prevArgs = arguments
if (!handle) {
fn(...prevArgs)
prevArgs = null
handle = setInterval(() => {
if (!prevArgs) {
handle = clearInterval(handle)
} else {
fn(...prevArgs)
prevArgs = null
}
}, delay)
}
}
}
Throttle, stores the last call arguments, and sets up an interval to fire until no past fires any more.
Similarities. They both have a delay time, and there's no fire during the delay, especially when there's only one fire. Both do not aggregate past events, so the number of events can be different than the actual fires.
Difference. The delay can be extended in debounce case with repeated events. Whereas the delay in the throttle case is fixed. So in general you get more fires from the throttle than debounce.
Easy to remember. Debounce groups bundle calls into one. Throttle keeps bundle calls within certain frequency.
Updated 1-20-23
Throttle might not need setInterval
, here's a new version I wrote recently which takes care of this
as well.
function throttle(fn, delay) {
let canFire = true
let queue = []
function pop() {
if (queue.length < 1) return
const [that, args] = queue.pop()
fn.apply(that, args)
canFire = false
setTimeout(() => {
canFire = true
pop()
}, delay)
}
function push() {
queue.push([this, arguments])
if (canFire) pop()
}
push.cancel = () => {
queue = []
}
return push
}
Updated 11-09-23
I start to believe throttle is an add-on on top of debounce. Read this https://windmaomao.medium.com/throttle-is-a-debounce-add-on-80d4a6027ad4.
function throttle(fn, delay) {
let h
let queue = []
function pop() {
if (queue.length < 1) return
if (!h) {
const [that, args] = queue.pop()
fn.apply(that, args)
h = setTimeout(() => {
h = null
pop()
}, delay)
}
}
return function push() {
queue.push([this, arguments])
pop()
}
}