Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

`throttle` — limit how often a function runs

`throttle` limits how often a function runs even when calls keep arriving. Use it, for example, to reduce the work done during scrolling.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const limited = throttle(fn, intervalMs, now);
limited(...args);
// Signature of the helper defined below; now is a function returning milliseconds.

throttle is a conventional name for a helper, not an ECMAScript built-in or a standard browser API. It returns a wrapper that limits how often fn starts. For example, you can update the interface less often while the user scrolls. Create the wrapper once and reuse it: each wrapper tracks its own last start time.

In this example, the first call runs fn immediately (leading edge). Another call can run fn once at least intervalMs has elapsed since the previous start. Calls that arrive too soon return undefined, do not extend the interval, and are not queued. An accepted call forwards this and the arguments, and passes through the result or exception from fn.

Other variants can run the latest pending call at the end of the interval (trailing edge). Here, the passage of time alone does not trigger a run. A typical trailing-edge debounce waits for a pause in calls; throttle can keep running the function even without a pause.

Supply a positive, finite interval and a clock function now that returns finite, nondecreasing values in milliseconds. The example uses a simulated clock; in a browser you can pass () => performance.now(). This is a web platform API, so check availability in your target runtime. If another variant uses setTimeout(), its callback may run later than scheduled.

Examples

{
  function throttle(fn, intervalMs, now) {
    let lastRun;
    return function (...args) {
      const time = now();
      if (lastRun !== undefined && time - lastRun < intervalMs) {
        return undefined;
      }
      lastRun = time;
      return Reflect.apply(fn, this, args);
    };
  }

  let time = 0;
  const panel = {
    prefix: "Update",
    update: throttle(function (label) {
      console.log(`${this.prefix}: ${label}`);
    }, 100, () => time),
  };

  panel.update("A");
  time = 40;
  panel.update("B");
  time = 100;
  panel.update("C");
  time = 140;
  panel.update("D");
}

Result

Update: A
Update: C

A runs at 0 ms, B is skipped at 40 ms, C runs at the exact 100 ms boundary, and D is skipped at 140 ms without running later.

Related lessons

  • JavaScript · Lesson 21 · Basic · Version: 4

Sources