TransWikia.com

I'd like to have a slightly altered behavior for lodash's throttle function

Stack Overflow Asked by Evert on November 15, 2021

Currently, if you set the wait option to 500, it will fire the underlying function at most once every 500 ms.

What I would like to have, is that the first time it’s called, it will wait 100 ms to fire, but then for subsequent calls it will only fire once every 500 ms. Then if more than 500 ms have passed since the last fire, it will go back to firing already after 100 ms for the first time.

Is there any easy way to adapt or combine some throttle and/or debounce functions together to create that kind of flow?

2 Answers

@Jonas Wilms, thank you for your answer. I didn't really like the use of Date and I found that writing a throttle function is actually quite trivial. At first I didn't know that, because lodash's throttle function is based on their debounce function and their debounce function looks a bit complicated to me.

Anyhow, I ended up writing this function, which seems to do the job.

export function throttle(fn, ...delays) {
  let t1, t2, activeDelay = 0

  return function() {
    if (t2) {
      clearTimeout(t2)
      t2 = undefined
    }

    if (t1) {
      return
    }

    t1 = setTimeout(() => {
      fn(...arguments)
      t1 = undefined

      // Increment the active delay each time
      // and then stick with the last one.
      activeDelay = Math.min(++activeDelay, delays.length - 1)

      // Set a 2nd `Timeout` that resets the
      // active delay back to the first one.
      t2 = setTimeout(() => {
        activeDelay = 0
        t2 = undefined
      }, delays[activeDelay])

    }, delays[activeDelay])
  }
}

Answered by Evert on November 15, 2021

You could maintain a date containing the time the last call was scheduled for:

 function throttle(fn, initial, cooldown) {
   let last = 0;
   return function throttled(...args) {
    setTimeout(fn, Math.max(0, cooldown + last - (last = Date.now())) || initial, ...args);
   }
 }

Answered by Jonas Wilms on November 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP