Throttling

The throttling pattern looks like the debouncing one, but instead of restarting a timer when the machine receives an event, it stops listening to events temporarily.

In the following example, when the machine receives the first click event, it goes into the Throttling state. The click event is not listened by the machine in this state. The Throttling state starts a timer of one second, which targets the Idle state.

Example

Try incrementing the counter by clicking the Increment button below. The counter will be incremented once every second.

The state machine is resilient to spamming. It controls how it should behave if the user abuses the button.

Count: 0

Throttling

Code

View in GitHub
machine.ts
import { assign, setup } from "xstate";
export const throttlingMachine = setup({
types: {
events: {} as { type: "click" } | { type: "reset" },
context: {} as { counter: number },
},
actions: {
"Increment counter": assign({
counter: ({ context }) => context.counter + 1,
}),
"Reset counter": assign({
counter: 0,
}),
},
}).createMachine({
id: "Throttling",
context: {
counter: 0,
},
initial: "Idle",
states: {
Idle: {
on: {
click: {
target: "Throttling",
actions: "Increment counter",
},
reset: {
actions: "Reset counter",
},
},
},
Throttling: {
after: {
"1000": {
target: "Idle",
},
},
},
},
});

Get news from XState by Example

Sign up for the newsletter to be notified when more machines or an interactive tutorial are released. I respect your privacy and will only send emails once in a while.