Skip to content

debounce

Delay a function until after a specified time has elapsed since the last call

248 bytes

Usage

The debounce function helps manage frequent function calls efficiently. It requires two inputs: a delay time (in milliseconds) and a callback. When you use the function returned by debounce (a.k.a. the “debounced function”), it doesn’t immediately run your callback. Instead, it waits for the specified delay.

If called again during this waiting period, it resets the timer. Your source function only runs after the full delay passes without interruption. This is useful for handling rapid events like keystrokes, ensuring your code responds only after a pause in activity.

import * as
import _
_
from 'radashi'
const
const processData: (data: string) => void
processData
= (
data: string
data
: string) => {
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
(`Processing data: "${
data: string
data
}"...`)
}
const
const debouncedProcessData: _.DebounceFunction<[data: string]>
debouncedProcessData
=
import _
_
.
debounce<[data: string]>({ delay, leading }: _.DebounceOptions, func: (data: string) => any): _.DebounceFunction<[data: string]>
export debounce

Returns a new function that will only call your callback after delay milliseconds have passed without any invocations.

The debounced function has a few methods, such as cancel, isPending, and flush.

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

@example

const myDebouncedFunc = debounce({ delay: 1000 }, (x) => {
console.log(x)
})
myDebouncedFunc(0) // Nothing happens
myDebouncedFunc(1) // Nothing happens
// Logs "1" about 1 second after the last invocation

@version12.1.0

debounce
({
DebounceOptions.delay: number
delay
: 100 },
const processData: (data: string) => void
processData
)
const debouncedProcessData: (data: string) => void
debouncedProcessData
('data1') // Never logs
const debouncedProcessData: (data: string) => void
debouncedProcessData
('data2') // Never logs
const debouncedProcessData: (data: string) => void
debouncedProcessData
('data3') // Processing data: "data3"...
function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)

Schedules execution of a one-time callback after delay milliseconds.

The callback will likely not be invoked in precisely delay milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.

When delay is larger than 2147483647 or less than 1, the delay will be set to 1. Non-integer delays are truncated to an integer.

If callback is not a function, a TypeError will be thrown.

This method has a custom variant for promises that is available using timersPromises.setTimeout().

@sincev0.0.1

@paramcallback The function to call when the timer elapses.

@paramdelay The number of milliseconds to wait before calling the callback.

@paramargs Optional arguments to pass when the callback is called.

setTimeout
(() => {
const debouncedProcessData: (data: string) => void
debouncedProcessData
('data4') // Processing data: "data4"... (200ms later)
}, 200)

Options

leading

When the leading option is true, your callback is invoked immediately the very first time the debounced function is called. After that, the debounced function works as if leading was false.

const
const myDebouncedFunc: _.DebounceFunction<[x: any]>
myDebouncedFunc
=
import _
_
.
debounce<[x: any]>({ delay, leading }: _.DebounceOptions, func: (x: any) => any): _.DebounceFunction<[x: any]>
export debounce

Returns a new function that will only call your callback after delay milliseconds have passed without any invocations.

The debounced function has a few methods, such as cancel, isPending, and flush.

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

@example

const myDebouncedFunc = debounce({ delay: 1000 }, (x) => {
console.log(x)
})
myDebouncedFunc(0) // Nothing happens
myDebouncedFunc(1) // Nothing happens
// Logs "1" about 1 second after the last invocation

@version12.1.0

debounce
({
DebounceOptions.delay: number
delay
: 100,
DebounceOptions.leading?: boolean

When true, your callback is invoked immediately the very first time the debounced function is called. After that, the debounced function works as if leading was false.

@defaultfalse

leading
: true },
x: any
x
=> {
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
(
x: any
x
)
})
const myDebouncedFunc: (x: any) => void
myDebouncedFunc
(0) // Logs "0" immediately
const myDebouncedFunc: (x: any) => void
myDebouncedFunc
(1) // Never logs
const myDebouncedFunc: (x: any) => void
myDebouncedFunc
(2) // Logs "2" about 100ms later

Methods

cancel

The cancel method of the debounced function does two things:

  1. It cancels any pending invocations of the debounced function.
  2. It permanently disables the debouncing behavior. All future invocations of the debounced function will immediately invoke your callback.
const
const myDebouncedFunc: _.DebounceFunction<[x: any]>
myDebouncedFunc
=
import _
_
.
debounce<[x: any]>({ delay, leading }: _.DebounceOptions, func: (x: any) => any): _.DebounceFunction<[x: any]>
export debounce

Returns a new function that will only call your callback after delay milliseconds have passed without any invocations.

The debounced function has a few methods, such as cancel, isPending, and flush.

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

@example

const myDebouncedFunc = debounce({ delay: 1000 }, (x) => {
console.log(x)
})
myDebouncedFunc(0) // Nothing happens
myDebouncedFunc(1) // Nothing happens
// Logs "1" about 1 second after the last invocation

@version12.1.0

debounce
({
DebounceOptions.delay: number
delay
: 100 },
x: any
x
=> {
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
(
x: any
x
)
})
const myDebouncedFunc: (x: any) => void
myDebouncedFunc
(0) // Never logs
const myDebouncedFunc: (x: any) => void
myDebouncedFunc
(1) // Never logs
const myDebouncedFunc: _.DebounceFunction<[x: any]>
myDebouncedFunc
.
function cancel(): void

When called, future invocations of the debounced function are no longer delayed and are instead executed immediately.

cancel
()
const myDebouncedFunc: (x: any) => void
myDebouncedFunc
(2) // Logs "2" immediately

flush

The flush method will immediately invoke your callback, regardless of whether the debounced function is currently pending.

const myDebouncedFunc = _.debounce({ delay: 100 }, x => {
console.log(x)
})
myDebouncedFunc(0) // Logs "0" about 100ms later
myDebouncedFunc.flush(1) // Logs "1" immediately

isPending

The isPending method returns true if there is any pending invocation of the debounced function.

const myDebouncedFunc = _.debounce({ delay: 100 }, x => {
console.log(x)
})
myDebouncedFunc(0) // Logs "0" about 100ms later
myDebouncedFunc.isPending() // => true
setTimeout(() => {
myDebouncedFunc.isPending() // => false
}, 100)