Skip to content

Instantly share code, notes, and snippets.

@beaucharman
Last active November 12, 2022 15:39
Show Gist options
  • Save beaucharman/e46b8e4d03ef30480d7f4db5a78498ca to your computer and use it in GitHub Desktop.
Save beaucharman/e46b8e4d03ef30480d7f4db5a78498ca to your computer and use it in GitHub Desktop.
An ES6 implementation of the throttle function. "Throttling enforces a maximum number of times a function can be called over time. As in 'execute this function at most once every 100 milliseconds.'" - CSS-Tricks (https://css-tricks.com/the-difference-between-throttling-and-debouncing/)
function throttle(callback, wait, immediate = false) {
let timeout = null
let initialCall = true
return function() {
const callNow = immediate && initialCall
const next = () => {
callback.apply(this, arguments)
timeout = null
}
if (callNow) {
initialCall = false
next()
}
if (!timeout) {
timeout = setTimeout(next, wait)
}
}
}
/**
* Normal event
* event | | |
* time ----------------
* callback | | |
*
* Call search at most once per 300ms while keydown
* keydown | | | |
* time -----------------
* search | |
* |300| |300|
*/
const input = document.getElementById('id')
const handleKeydown = throttle((arg, event) => {
console.log(`${event.type} for ${arg} has the value of: ${event.target.value}`)
}, 300)
input.addEventListener('keydown', (event) => {
handleKeydown('input', event)
})
@FRSgit
Copy link

FRSgit commented Jun 5, 2019

Made typescript (and a little simpler/more efficient) variation of debounce (!) function (without immediate call).
Hopefully someone finds it useful 😄

const throttle = <T extends []> (
  callback: (..._: T) => void,
  wait: number
): (..._: T) => void => {
  const next = () => {
    timeout = clearTimeout(timeout) as undefined;
    callback(...lastArgs);
  };
  let timeout: NodeJS.Timeout | undefined;
  let lastArgs: T;

  return (...args: T) => {
    lastArgs = args;

    if (timeout === void 0) {
      timeout = setTimeout(next, wait);
    }
  };
};

@OmShiv
Copy link

OmShiv commented Aug 12, 2019

This isn't a throttle, it's a debounce.

💯

The author has duly noted the definition: Throttling enforces a maximum number of times a function can be called over time
But in the code example, the throttle function doesn't accept any params for setting the maximum number of times.

In his example, execute this function at most once every 100 milliseconds
throttle should receive:

throttle(callback, 1, 100); 
// callback => function to throttle
// 1 => at most once
// 100 => interval for this rate-limiting.

Similarly, for execute this function at most twice every 500 milliseconds

throttle(callback, 2, 500);

In fact, what author has provided is really a debounce function.

@robertmirro
Copy link

It appears there are varying opinions on throttle functionality. 😄

My version of throttle should:

  • execute immediately the first time it's invoked, unlike debounce, which waits until its idle time is exceeded before initially executing. result: immediate visual feedback
  • not execute if invoked again before the wait time has been exceeded. result: reduce jank
  • queue the latest denied execution to be re-invoked if possible when the wait time has been exceeded. result: ensure final invocation occurs
const throttle = (fn, wait) => {
    let previouslyRun, queuedToRun;

    return function invokeFn(...args) {
        const now = Date.now();

        queuedToRun = clearTimeout(queuedToRun);

        if (!previouslyRun || (now - previouslyRun >= wait)) {
            fn.apply(null, args);
            previouslyRun = now;
        } else {
            queuedToRun = setTimeout(invokeFn.bind(null, ...args), wait - (now - previouslyRun));    
        }
    }
}; 

const test = throttle(wait => { console.log(`INVOKED (${wait})`, Date.now()) }, 100);

for(let i = 0, wait = 0; i < 20; i++) {
    wait += 30;
    setTimeout(() => { test(wait); }, wait)
}

@OmShiv
Copy link

OmShiv commented Sep 20, 2019

It appears there are varying opinions on throttle functionality. 😄

Right. Your solution also appears to be a throttle. The author's solution, however, appears purely a debounce.

@ankitarora05
Copy link

ankitarora05 commented Oct 19, 2019

To throttle a function means to ensure that the function is called at most once in a specified time period (for instance, once every 5 seconds).

function throttle(f, t) {
  return function (args) {
    let previousCall = this.lastCall;
    this.lastCall = Date.now();
    if (previousCall === undefined // function is being called for the first time
        || (this.lastCall - previousCall) > t) { // throttle time has elapsed
      f(args);
    }
  }
}

@robertmirro
Copy link

As you just proved... There are varying opinions. 😜

@OmShiv
Copy link

OmShiv commented Oct 21, 2019

@ankitarora05

To throttle a function means to ensure that the function is called at most once in a specified time period

Not necessarily once. It could be at most X times in a specified time period. So the solution function which throttles a given function should receive 3 params

  • the number of times to call (in your case, that is 1)
  • the specified period of time
  • the callback function itself.

@vacilar
Copy link

vacilar commented Jan 9, 2020

Use RxJs and you'll be happy 😀

@undergroundwires
Copy link

Typescript version of throttle function with final and immediate invocations

// Throttle with ensured final and immediate invocations
const throttle = <T extends []> (callback: (..._: T) => void, wait: number): (..._: T) => void => {
    let queuedToRun: NodeJS.Timeout | undefined;
    let previouslyRun: number;
    return function invokeFn(...args: T) {
        const now = Date.now();
        queuedToRun = clearTimeout(queuedToRun) as undefined;
        if (!previouslyRun || (now - previouslyRun >= wait)) {
            callback(...args);
            previouslyRun = now;
        } else {
            queuedToRun = setTimeout(invokeFn.bind(null, ...args), wait - (now - previouslyRun));
        }
    };
};

Thanks to @robertmirro and @FRSgit

@FRSgit
Copy link

FRSgit commented Sep 19, 2021

Nice one @undergroundwires! But I've skipped leading invocation on purpose, because I was aiming for the simplest implementation. Also, I found out that having this immediate leading method firing is not always a good idea, but that of course depends on a use case.

If we want to write the "fullest" throttle fn I think there should be a possibility to opt out from leading & trailing callback calls. Exactly as they do in lodash.

@benneq
Copy link

benneq commented Nov 12, 2022

Here's my version, using TypeScript. It's returning a callback to cancel the timeout, useful if use have to use some cleanup function.

const throttle = <TArgs extends unknown[] = []>(
  callback: (...args: TArgs) => void
): ((ms: number, ...args: TArgs) => (() => void)) => {
  let timeout: NodeJS.Timeout | undefined;
  let lastArgs: TArgs;

  const cancel = () => {
    clearTimeout(timeout);
  };

  return (ms, ...args) => {
    lastArgs = args;

    if (!timeout) {
      timeout = setTimeout(() => {
        callback(...lastArgs);
        timeout = undefined;
      }, ms);
    }

    return cancel;
  };
};

Usage:

const cb = (n) => console.log(n);
const throttledCb = throttle(cb);
throttledCb(100, 1);
// wait 50ms
throttledCb(100, 2);
// wait 50ms
// prints 2

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