typescript 39 lines · 7 steps

Building a trailing-edge throttle in TypeScript

A generic throttle that runs immediately when allowed and otherwise schedules one trailing call, used to drive a scroll progress bar.

Explained by highlit
1function throttle<T extends (...args: any[]) => void>(
2 fn: T,
3 limit: number
4): (...args: Parameters<T>) => void {
5 let lastRun = 0;
6 let queued: ReturnType<typeof setTimeout> | null = null;
7 
8 return function (this: unknown, ...args: Parameters<T>) {
9 const now = Date.now();
10 const remaining = limit - (now - lastRun);
11 
12 if (remaining <= 0) {
13 if (queued) {
14 clearTimeout(queued);
15 queued = null;
16 }
17 lastRun = now;
18 fn.apply(this, args);
19 } else if (!queued) {
20 queued = setTimeout(() => {
21 lastRun = Date.now();
22 queued = null;
23 fn.apply(this, args);
24 }, remaining);
25 }
26 };
27}
28 
29const progressBar = document.querySelector<HTMLElement>('#reading-progress');
30 
31const updateProgress = throttle(() => {
32 if (!progressBar) return;
33 const scrollTop = window.scrollY;
34 const docHeight = document.documentElement.scrollHeight - window.innerHeight;
35 const percent = docHeight > 0 ? (scrollTop / docHeight) * 100 : 0;
36 progressBar.style.width = `${Math.min(percent, 100)}%`;
37}, 100);
38 
39window.addEventListener('scroll', updateProgress, { passive: true });
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1A throttle bounds how often a function runs by tracking the timestamp of the last execution.
  2. 2Scheduling a trailing call ensures the final invocation isn't lost when events stop mid-window.
  3. 3Generic constraints with Parameters<T> let one wrapper preserve any function's signature type-safely.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
javascript
function evaluate(expression) {
  const tokens = tokenize(expression);
  let pos = 0;
 

Building a recursive descent calculator

parsing recursion operator-precedence
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps

Share this explainer

Here's the card — post it anywhere.

Building a trailing-edge throttle in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code