Throttle
Throttle execution of a function. Especially useful for rate limiting execution of handlers on events like resize and scroll.
Usage
<script>
import {throttle} from "@sveu/shared"
let smashed = 0
let updated = 0
const smash_throttled = throttle(() => {
updated++
}, 2)
</script>
<h4>Delay is set to 2 second for this demo.</h4>
<button on:click="{() => {smashed++;smash_throttled()}}">Smash me!</button>
<p>Button Smashed: {smashed }</p>
<p>Event handler called: { updated }</p>
<script>
import {throttle} from "@sveu/shared"
let smashed = 0
let updated = 0
const smash_throttled = throttle(() => {
updated++
}, 2)
</script>
<h4>Delay is set to 2 second for this demo.</h4>
<button on:click="{() => {smashed++;smash_throttled()}}">Smash me!</button>
<p>Button Smashed: {smashed }</p>
<p>Event handler called: { updated }</p>
svelte
Example
Delay is set to 2 second for this demo.
Button Smashed: 0
Event handler called: 0
<script>
import { throttle } from "@sveu/shared"
let smashed = 0
let updated = 0
const smash_throttled = throttle(() => {
updated++
}, 2)
</script>
<div class="space-y-4 text-center">
<h4>Delay is set to 2 second for this demo.</h4>
<button on:click="{() => {
smashed++
smash_throttled()
}}">
Smash me!
</button>
<p>Button Smashed: {smashed}</p>
<p>Event handler called: {updated}</p>
</div>
<script>
import { throttle } from "@sveu/shared"
let smashed = 0
let updated = 0
const smash_throttled = throttle(() => {
updated++
}, 2)
</script>
<div class="space-y-4 text-center">
<h4>Delay is set to 2 second for this demo.</h4>
<button on:click="{() => {
smashed++
smash_throttled()
}}">
Smash me!
</button>
<p>Button Smashed: {smashed}</p>
<p>Event handler called: {updated}</p>
</div>
svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Click fold/expand code
API
Arguments
Name | Description | Type | Required |
---|---|---|---|
fn | Function to execute | Function | Yes |
s | Time to wait before executing fn in second | number | Yes |
trailing | Call fn again after the time is up | boolean | No |
leading | Call fn immediately | boolean | No |