javascript
39 lines · 6 steps
Building a leading-and-trailing throttle
A closure-based throttle that fires immediately, then guarantees a trailing call for events that arrive during the cooldown.
Explained by
highlit
1function throttle(fn, wait) {
2 let lastCall = 0;
3 let timeoutId = null;
4 let lastArgs = null;
5 let lastThis = null;
6
7 function invoke() {
8 lastCall = Date.now();
9 timeoutId = null;
10 fn.apply(lastThis, lastArgs);
11 lastArgs = lastThis = null;
12 }
13
14 function throttled(...args) {
15 const now = Date.now();
16 const remaining = wait - (now - lastCall);
17 lastArgs = args;
18 lastThis = this;
19
20 if (remaining <= 0) {
21 if (timeoutId) {
22 clearTimeout(timeoutId);
23 timeoutId = null;
24 }
25 invoke();
26 } else if (!timeoutId) {
27 timeoutId = setTimeout(invoke, remaining);
28 }
29 }
30
31 throttled.cancel = function () {
32 clearTimeout(timeoutId);
33 timeoutId = null;
34 lastCall = 0;
35 lastArgs = lastThis = null;
36 };
37
38 return throttled;
39}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Closures let a returned function carry private state like timers and timestamps across calls.
- 2Capturing both args and this keeps a deferred trailing invocation faithful to the original call site.
- 3Exposing a cancel method gives callers a way to clear pending timers and avoid stale invocations.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-leading-and-trailing-throttle-explained-javascript-da62/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.