App patterns · real, tested code

Debounce and Throttle a Function in Larzscript

Two different ways to rate-limit how often a function actually runs: debounce waits for a quiet gap, throttle guarantees a minimum spacing.

Both close over a 'last call' timestamp read from clock() (monotonic, so it's immune to wall-clock adjustments) - no package needed, just closures and a comparison.

Code

fn debounce(fn_, wait_seconds) {
  let last_call = 0.0
  return fn(x) {
    let now = clock()
    if now - last_call >= wait_seconds {
      last_call = now
      return fn_(x)
    }
    return nil
  }
}

fn throttle(fn_, interval_seconds) {
  let last_run = 0.0
  return fn(x) {
    let now = clock()
    if now - last_run >= interval_seconds {
      last_run = now
      fn_(x)
      return true
    }
    return false
  }
}

let debounced = debounce(fn(x) { print("debounced call:", x) }, 0.2)
debounced(1)
debounced(2)
sleep(0.25)
debounced(3)

let throttled = throttle(fn(x) { print("throttled call:", x) }, 0.2)
print(throttled(1))
print(throttled(2))
sleep(0.25)
print(throttled(3))
Output
debounced call: 1
debounced call: 3
throttled call: 1
true
false
throttled call: 3
true