What is the correct type when dealing with timers? I have tried Timeout
and number
let debounceResize: any;
// ^ What should this be?
window.addEventListener('resize', () => {
clearTimeout(debounceResize);
debounceResize = setTimeout(calcCanvasSize, 500);
});
setTimeout() is a method used to call a function after a specified amount of time in milliseconds. This method acts as a timer and executes the code after the timer expires. setTimeout() cannot be executed multiple times; it can only be executed once.
The setTimeout() returns a timeoutID which is a positive integer identifying the timer created as a result of calling the method. The timeoutID can be used to cancel timeout by passing it to the clearTimeout() method.
The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);
For this case, I will give you 2 options:
debounceResize
as return type of setTimeout
, use ReturnType
native generic.let debounceResize: ReturnType<typeof setTimeout>;
window.setTimeout
instead of only setTimeout
. window.setTimeout
returns a number.let debounceResize: number;
debounceResize = window.setTimeout(() => {}, 1000);
In a Web Browser app, setTimeout
returns a number
.
This setup requires the DOM
library (or equivalent).
In a NodeJS app, setTimeout
returns a NodeJS.Timeout
.
npm install @types/node --save-dev`.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With