Skip to content

Instantly share code, notes, and snippets.

@beaucharman
Last active November 12, 2022 15:39
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • 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)
})
@cytronn
Copy link

cytronn commented Nov 19, 2016

have you any Idea on how to implement the trailing and leading parameters present in _.js ?

@hallister
Copy link

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

@beaucharman
Copy link
Author

This is a throttle function, @hallister :)

From CSS-Tricks:

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."

Notice how the return closure only will fire on each call if it's timeout has ended.

In the this debounce function, it "enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."

x

@webeli
Copy link

webeli commented Jun 7, 2017

Cool and simple.

@simonsmith
Copy link

Nice implementation. You can also avoid leaning on arguments in ES6:

  return (...args) => {
    if (!timeout) {
      callbackArgs = args;
      timeout = setTimeout(later, wait);
    }
  };

@chadwilken
Copy link

Very nice

@LakeVostok
Copy link

LakeVostok commented Oct 16, 2017

In the correct implementation, the first call of the function occurs immediately. The next call, if less than the delay time passed, is ignored, but if it is the last, then a call occurs. Yours gist implements delay. Maybe you wanted to implement debounce?

function debounce(callback, delay) {
  var timer = null;

  return function() {
    if (timer) return;

    callback.apply(this, arguments);
    timer = setTimeout(() => timer = null, delay);
  }
}

Here is throttle function:

function throttle(callback, delay) {
  let isThrottled = false, args, context;

  function wrapper() {
    if (isThrottled) {
      args = arguments;
      context = this;
      return;
    }

    isThrottled = true;
    callback.apply(this, arguments);
    
    setTimeout(() => {
      isThrottled = false;
      if (args) {
        wrapper.apply(context, args);
        args = context = null;
      }
    }, delay);
  }

  return wrapper;
}

And to see the difference:

let logger = console.log;

let dlogger = debounce(logger, 5000);
dlogger(1); //log 1
dlogger(2); //ignore
dlogger(3); //ignore
setTimeout(() => dlogger(4), 5000) //log 4

let tlogger = throttle(logger, 5000);
tlogger(1); //log 1
tlogger(2); //ignore
setTimeout(() => tlogger(3), 5000) //log 3
tlogger(4); //last call waits 5 second and then log 4

let ylogger = yours_throttle(logger, 5000);
tlogger(1); //waits 5 second and then log 1
tlogger(2); //ignore
tlogger(3); //ignore

@msand
Copy link

msand commented Dec 14, 2017

I made a variation of these patterns, for throttling promise returning functions, in the context of toggling the state of something and causing mutation requests to be sent over the network. This is to wrap the event handler, such that if a user clicks the action twice in fast succession, only the first is responded to and the second is considered a mistake. And, if they clicked by mistake to begin with, and click once more to undo slightly later, it queues the reverse/undo action to be sent, once the first action succeeds.

import promiseLimit from "promise-limit";
function throttleFirstTimeout(fn, window) {
  let isThrottled = false;
  let promise = null;

  function wrapper() {
    if (isThrottled) {
      return promise;
    }

    isThrottled = true;
    setTimeout(() => {
      isThrottled = false;
      promise = null;
    }, window);

    promise = fn();

    return promise;
  }

  return wrapper;
}
function throttleFirstNow(fn, window) {
  let promise = null;
  let last = 0;

  function wrapper() {
    const now = Date.now();
    if (last !== 0 && now - last < window) {
      return promise;
    }

    last = now;
    promise = null;
    promise = fn();
    return promise;
  }

  return wrapper;
}
function throttleLimit(fn, concurrency, window) {
  const limited = promiseLimit(concurrency);
  function throttleFn() {
    return limited(fn);
  }
  return throttleFirstNow(throttleFn, window);
}
let i = 0;
function testPromiseReturningFunction(networkTime = 600) {
  return new Promise(resolve => setTimeout(() => resolve(i++), networkTime));
}
const throttled = throttleLimit(testPromiseReturningFunction, 1, 500);
const test = () =>
  throttled().then(j => console.log(j, new Date().getMilliseconds()));
test();
test();
setTimeout(test, 100);
setTimeout(test, 200);
setTimeout(test, 600);
setTimeout(test, 700);

Test example:
https://www.webpackbin.com/bins/-L0JghsIOjutzhCxmkqB

@matthew-ia
Copy link

Thanks! This is the only implementation I could find that worked out-of-the-box. Great stuff!

@tkafka
Copy link

tkafka commented Apr 24, 2019

I think you can move the definition of next into throttle - it won't be needlessly redefined on each call that way.

@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