Skip to content

defer

Defer the execution of a function until the current execution stack is cleared.

Basic Usage

typescript
import { defer } from 'radash'

const deferred = defer(() => {
  console.log('This will execute after the current execution stack is cleared')
})

console.log('This will execute first')
// Output:
// This will execute first
// This will execute after the current execution stack is cleared

Syntax

typescript
function defer<T extends (...args: any[]) => any>(
  fn: T
): (...args: Parameters<T>) => void

Parameters

  • fn (T): The function to defer execution

Return Value

Returns a function that will execute the original function after the current execution stack is cleared.

Examples

Basic Deferred Execution

typescript
import { defer } from 'radash'

const deferredFn = defer(() => {
  console.log('Deferred execution')
})

console.log('Immediate execution')
deferredFn()
console.log('Synchronous execution')

// Output:
// Immediate execution
// Synchronous execution
// Deferred execution

Passing Parameters

typescript
import { defer } from 'radash'

const deferredSum = defer((a: number, b: number) => {
  console.log(`Deferred calculation: ${a} + ${b} = ${a + b}`)
})

deferredSum(5, 3)
console.log('This will execute first')

// Output:
// This will execute first
// Deferred calculation: 5 + 3 = 8

Handling Async Operations

typescript
import { defer } from 'radash'

const deferredAsync = defer(async () => {
  console.log('Starting async operation')
  await new Promise(resolve => setTimeout(resolve, 100))
  console.log('Async operation completed')
})

deferredAsync()
console.log('Synchronous code execution')

// Output:
// Synchronous code execution
// Starting async operation
// Async operation completed

Using in Event Handlers

typescript
import { defer } from 'radash'

const handleClick = defer(() => {
  console.log('Button was clicked')
})

// Simulate button click
console.log('Preparing to click')
handleClick()
console.log('Click event triggered')

// Output:
// Preparing to click
// Click event triggered
// Button was clicked

Error Handling

typescript
import { defer } from 'radash'

const deferredError = defer(() => {
  throw new Error('Deferred execution error')
})

try {
  deferredError()
  console.log('This line will execute')
} catch (error) {
  console.log('Error caught:', error.message)
}

// Output:
// This line will execute
// Error caught: Deferred execution error

Combining with Promises

typescript
import { defer } from 'radash'

const deferredPromise = defer(() => {
  return Promise.resolve('Deferred Promise result')
})

console.log('Starting execution')
deferredPromise().then(result => {
  console.log('Promise result:', result)
})
console.log('Synchronous code ended')

// Output:
// Starting execution
// Synchronous code ended
// Promise result: Deferred Promise result

Cleanup Operations

typescript
import { defer } from 'radash'

const cleanup = defer(() => {
  console.log('Executing cleanup operation')
})

console.log('Starting work')
// ... some work ...
cleanup()
console.log('Work completed')

// Output:
// Starting work
// Work completed
// Executing cleanup operation

Notes

  1. Execution timing: The function will execute after the current execution stack is cleared, usually in the next event loop
  2. Parameter passing: The deferred function will receive all parameters passed at the time of calling
  3. Error handling: If an error occurs during deferred execution, the error will be thrown to the global scope
  4. Return value: If the deferred function has a return value, it will be ignored
  5. Performance: Implemented using setTimeout(fn, 0) or setImmediate

Differences from Other Methods

  • setTimeout(fn, 0): Same functionality, but defer is more concise
  • setImmediate(): Similar functionality in Node.js environment
  • queueMicrotask(): Executes in the next microtask, not macro task
  • Promise.resolve().then(): Microtask, different execution timing

Practical Application Scenarios

  1. Event handling: Defer handling of user interaction events
  2. Cleanup operations: Execute cleanup before function returns
  3. Logging: Defer logging to avoid blocking the main flow
  4. State updates: Defer UI state updates
  5. Error handling: Defer error handling to ensure main flow is not affected

Released under the MIT License.