Skip to main content

useTimeout

Purpose

Set a function that will be called after given time has elapsed, and will automatically cleaned up on controller disconnect if that happens before the timeout is called. 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 to be run after the provided interval.

Usage

useTimeout

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 before the handler function is run.
Return ValuesTypePurpose
teardownFunctionCall this function if you want to cancel the timeout before the scheduled time

How to Use


import {Controller} from '@hotwired/stimulus';
import {useTimeout} from 'stimulus-library';

export default class extends Controller {

connect() {
// Run `handler` after 5 seconds
useTimeout(this, this.handler, 5000)

// Setup `handler` to run after 5 seconds, but cancel it before the scheduled time
let cleanupTimeout = useTimeout(this, this.handler, 5000)
cleanupTimeout();
}

handler() {
console.log('Look at me run!')
}

}