Reading history

JavaScript Higher-Order Functions, Debounce and Throttle

5 min read 0 views

Learn JavaScript higher-order functions: callbacks, function factories, compose and pipe, memoization, currying, and debounce and throttle for events.

In JavaScript a function is a value, just like a number or a string. You can store it in a variable, pass it to another function, or return it from one. A higher-order function is any function that takes or returns another function. You already use them with map, filter and addEventListener. This lesson shows how to write your own, including the debounce and throttle helpers used on almost every interactive site.

In this lesson you will learn

  • Passing functions as arguments (callbacks)
  • Returning functions to create specialised versions
  • Composing small functions into a pipeline
  • Caching results with memoisation
  • Debounce and throttle for fast-firing events

This lesson builds on Functions, especially closures, and array methods.

Taking and Returning Functions

// Functions are values: they can be passed in and returned
function repeat(n, action) {
  for (let i = 1; i <= n; i++) action(i);
}
repeat(3, i => console.log("Round", i));

// A function that returns a function
function multiplier(factor) {
  return x => x * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(7), triple(7));

// Composing small functions into a pipeline
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const slugify = pipe(
  s => s.trim(),
  s => s.toLowerCase(),
  s => s.replace(/[^a-z0-9]+/g, "-"),
  s => s.replace(/^-|-$/g, "")
);
console.log(slugify("  Hello World: JS Tips! "));

// Memoize: remember results of slow calls
function memoize(fn) {
  const cache = new Map();
  return n => {
    if (!cache.has(n)) cache.set(n, fn(n));
    return cache.get(n);
  };
}
let calls = 0;
const square = memoize(n => { calls++; return n * n; });
console.log(square(9), square(9), square(9), "computed", calls, "time(s)");

Output

Round 1
Round 2
Round 3
14 21
hello-world-js-tips
81 81 81 computed 1 time(s)
  • repeat(n, action) takes a function and decides when to call it. The caller decides what happens each round.
  • multiplier(2) returns a new function that remembers factor through a closure. One factory makes as many specialised functions as you need.
  • pipe(...fns) returns a function that passes a value through each step in order, using reduce. slugify is built from four tiny, testable steps and turns a title into a URL-friendly slug.
  • memoize wraps a function with a cache stored in a Map. The square of 9 is computed once and then served from memory, which matters for slow calculations or repeated network requests.

Debounce and Throttle

// debounce: run only after calls stop for "wait" ms
function debounce(fn, wait) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), wait);
  };
}
// throttle: run at most once every "wait" ms
function throttle(fn, wait) {
  let last = -Infinity;
  return (...args) => {
    const now = Date.now();
    if (now - last >= wait) { last = now; fn(...args); }
  };
}

const search = debounce(q => console.log("debounced search for:", q), 100);
const save = throttle(n => console.log("throttled save #" + n), 1000);

// Simulate fast typing: j, ja, jav, java, 20 ms apart
["j", "ja", "jav", "java"].forEach((q, i) => setTimeout(() => search(q), i * 20));
// Simulate 5 quick save clicks
for (let n = 1; n <= 5; n++) save(n);

Output

throttled save #1
debounced search for: java
  • Events such as typing, scrolling and resizing can fire dozens of times per second. Running heavy work on each one wastes effort.
  • Debounce waits until the calls stop for a set time. Each new call cancels the previous timer with clearTimeout, so after four quick keystrokes only one search runs, for the final text “java”. Use it for search boxes and auto-save.
  • Throttle runs at most once per period. Five rapid clicks produce a single save. Use it for scroll and resize handlers or to stop double submissions.
  • Both helpers return a new function and keep their state (timer, last) in a closure, a typical higher-order pattern.

In a page, attach the wrapped version: input.addEventListener("input", debounce(e => search(e.target.value), 300));

Built-in Higher-Order Functions

FunctionTakes a function to…
arr.map(fn)Transform each item
arr.filter(fn)Decide which items to keep
arr.reduce(fn, start)Combine items into one value
arr.sort(fn)Compare two items
arr.find(fn), some, everyTest items
setTimeout(fn, ms)Run later
el.addEventListener(type, fn)Run when something happens
promise.then(fn)Run when a result is ready

Common Mistakes

  1. Calling instead of passing: setTimeout(save(), 1000) runs save immediately. Pass save or () => save().
  2. Creating a new debounced function on every event, which gives each call its own timer so nothing is debounced. Create it once.
  3. Memoising functions with side effects or results that change over time.
  4. Over-abstracting: a plain loop is fine when a pipeline would be harder to read.

Practice Exercises

Exercise 1. Write once(fn) that returns a function which runs fn only the first time it is called.

Show answer
function once(fn) {
  let done = false, result;
  return (...args) => {
    if (!done) { done = true; result = fn(...args); }
    return result;
  };
}
const init = once(() => console.log("Initialised"));
init(); init();   // prints once

Exercise 2. Write a curried add(a)(b)(c) that returns the sum of three numbers.

Show answer
const add = a => b => c => a + b + c;
console.log(add(1)(2)(3));   // 6
const addTen = add(10);      // partially applied
console.log(addTen(5)(5));   // 20

Frequently Asked Questions

What is the difference between a callback and a higher-order function?

The higher-order function is the one that receives or returns a function, such as map. The callback is the function being passed in.

How long should a debounce delay be?

For search-as-you-type, 250 to 400 milliseconds feels responsive without sending a request on every key. For saving drafts, a second or two is common.

Summary

  • Functions are values: pass them in and return them.
  • Function factories and closures create specialised functions.
  • Compose small functions into pipelines; memoise expensive pure ones.
  • Debounce waits for a pause; throttle limits the rate.

Next: The JavaScript Event Loop.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *