useInterval
Purpose
Set a function that will be called periodically at the given interval, and automatically cleaned up on controller disconnect
.
Automatically sets the correct Javascript binding so that this
inside the event listener corresponds to the controller instance.
Side Effects
The controller will use setInterval
to register the given callback at the provided interval.
Usage
useInterval
Parameters | Type | Purpose | Default | |
---|---|---|---|---|
controller | Controller | The instance of the controller to install the behaviour on. This allows the mixin to automatically register cleanup on the controller's disconnect . | ||
callback | Function | A function to run after the elapsed time | ||
timeout | Integer | The time in ms between each handler function being run. |
Return Values | Type | Purpose | ||
---|---|---|---|---|
teardown | Function | Call this function if you want to cancel the interval |
How to Use
import {Controller} from '@hotwired/stimulus';
import {useInterval} from 'stimulus-library';
export default class extends Controller {
connect() {
// Run `handler`every 5 seconds until disconnect.
useInterval(this, this.handler, 5000)
}
handler() {
console.log('Look at me run!')
}
}