Skip to main content

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​

ParametersTypePurposeDefault
controllerControllerThe instance of the controller to install the behaviour on. This allows the mixin to automatically register cleanup on the controller's disconnect.
callbackFunctionA function to run after the elapsed time
timeoutIntegerThe time in ms between each handler function being run.
Return ValuesTypePurpose
teardownFunctionCall 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!')
}
}