Skip to content

throttle

Creates a throttled function that limits invocations to a specified interval

260 bytes

Usage

The throttle function creates a new function that, when called, will only execute the original function at most once per specified time interval. This is useful for limiting the rate at which a function can fire, especially for performance-intensive operations like handling scroll or resize events.

The function accepts two parameters:

  1. An options object with:
    • interval: The minimum time (in milliseconds) between function invocations
    • trailing (optional): If true, also calls the function after the throttle period if it was invoked during the throttle
  2. The function to be throttled

The returned throttled function also includes these methods:

  • isThrottled(): boolean: To check if there’s currently an active throttle
  • trigger(...args): void: To invoke the wrapped function without waiting for the next interval
import * as
import _
_
from 'radashi'
// Throttle a scroll event handler
const
const handleScroll: () => void
handleScroll
= () => {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
('Scroll position:',
any
window
.
any
scrollY
)
}
const
const throttledScroll: _.ThrottledFunction<[]>
throttledScroll
=
import _
_
.
throttle<[]>({ interval, trailing }: {
interval: number;
trailing?: boolean;
}, func: () => any): _.ThrottledFunction<[]>
export throttle

Given an interval and a function returns a new function that will only call the source function if interval milliseconds have passed since the last invocation.

@seehttps://radashi.js.org/reference/curry/throttle

@example

const sup = throttle({ interval: 1000 }, () => {
console.log("sup")
})
sup() // => logs "sup"
sup() // => no logs
setTimeout(() => sup(), 500) // => no logs
setTimeout(() => sup(), 1000) // => logs "sup"

@version12.1.0

throttle
({
interval: number
interval
: 200 },
const handleScroll: () => void
handleScroll
)
any
window
.
any
addEventListener
('scroll',
const throttledScroll: _.ThrottledFunction<[]>
throttledScroll
)
// Throttle an API call
const
const throttledFetch: _.ThrottledFunction<[]>
throttledFetch
=
import _
_
.
throttle<[]>({ interval, trailing }: {
interval: number;
trailing?: boolean;
}, func: () => any): _.ThrottledFunction<[]>
export throttle

Given an interval and a function returns a new function that will only call the source function if interval milliseconds have passed since the last invocation.

@seehttps://radashi.js.org/reference/curry/throttle

@example

const sup = throttle({ interval: 1000 }, () => {
console.log("sup")
})
sup() // => logs "sup"
sup() // => no logs
setTimeout(() => sup(), 500) // => no logs
setTimeout(() => sup(), 1000) // => logs "sup"

@version12.1.0

throttle
(
{
interval: number
interval
: 5000,
trailing?: boolean
trailing
: true },
async () => {
const
const response: Response
response
= await
function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>
fetch
('https://api.example.com/data')
const
const data: unknown
data
= await
const response: Response
response
.
BodyMixin.json: () => Promise<unknown>
json
()
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const data: unknown
data
)
},
)
// Check if throttled
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
('Is throttled:',
const throttledFetch: _.ThrottledFunction<[]>
throttledFetch
.
function isThrottled(): boolean

Checks if there is any invocation throttled

isThrottled
())

Timing

A visual representation of the throttle behavior when interval is set to 200ms:

Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -
Throttle Invocations: x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x - - -
Source Invocations: x - - - - - - - - - - - - x - - - - - - - - - - - - - x - - - - - -

When the trailing option is set to true, an additional invocation occurs after the throttle period if any calls were made during the throttled time:

Time: 0ms - - - - 100ms - - - - 200ms - - - - 300ms - - - - 400ms - - - -
Throttle Invocations: x x x x x x x x x x x x x x x x x x x x x - - - - - - - - - - - - -
Source Invocations: x - - - - - - - - - - - - x - - - - - - - - - - - - - x - - - - - -

In this diagram, ‘x’ represents function invocations, and ’-’ represents time passing.