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
Related
Retry with Exponential Backoff in LarzscriptRetry a flaky call a few times, waiting longer between each attempt, instead of failing on the first hiccup or hammering a struggling service.→Memoize a Function in LarzscriptCache a function's results so calling it twice with the same input only does the real work once.→Implement a State Machine in LarzscriptDeclare states and transitions, fire events, and let the machine reject anything that isn't a legal move - a document workflow (draft -> review -> published) in a few lines.→Paginate a List in LarzscriptSlice a list into pages with the has_next/has_prev/1-based-index bookkeeping every list-showing page needs, without hand-rolling the off-by-one math again.→