Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: What is the correct type for a Timeout?

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);
  });

enter image description here enter image description here enter image description here

like image 801
Bill Avatar asked Feb 16 '20 05:02

Bill


People also ask

What is the type of setTimeout in TypeScript?

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.

What set timeout returns?

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.

What is the syntax of setTimeout?

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);


2 Answers

For this case, I will give you 2 options:

  1. Define type of debounceResize as return type of setTimeout, use ReturnType native generic.
let debounceResize: ReturnType<typeof setTimeout>;
  1. Use window.setTimeout instead of only setTimeout. window.setTimeout returns a number.
let debounceResize: number;

debounceResize = window.setTimeout(() => {}, 1000);
like image 80
hoangdv Avatar answered Oct 19 '22 16:10

hoangdv


In a Web Browser app, setTimeout returns a number.

This setup requires the DOM library (or equivalent).

enter image description here

In a NodeJS app, setTimeout returns a NodeJS.Timeout.

npm install @types/node --save-dev`. 

enter image description here

like image 31
Shaun Luttin Avatar answered Oct 19 '22 17:10

Shaun Luttin