Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - what type is f.e. setInterval

If I'd like to assign a type to a variable that will later be assigned a setInterval like so:

this.autoSaveInterval = setInterval(function(){
      if(this.car.id){
        this.save();
      }
      else{
        this.create();
      }
    }.bind(this), 50000);

What type should be assigned to this.autosaveInterval vairable?

like image 440
gfels Avatar asked Jul 17 '18 08:07

gfels


People also ask

What is the TypeScript type of setInterval?

setInterval TypeScript is a method used to repeat specific function with every given time intervals. setInterval() will evaluate expressions or calls a function at certain intervals.

Is setInterval a callback function?

Introduction to JavaScript setInterval() The setInterval() repeatedly calls a function with a fixed delay between each call. In this syntax: The callback is a callback function to be executed every delay milliseconds.

Is setInterval a function?

Usage notesThe setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using clearInterval() . If you wish to have your function called once after the specified delay, use setTimeout() .

Is setInterval synchronous or asynchronous?

setTimeout and setInterval are the only native functions of the JavaScript to execute code asynchronously.


3 Answers

Late to the party, but the best type (especially since the type is opaque, we only care that we can pass it to clearInterval() later) might be the automatically deduced one, ie. something like:

ReturnType<typeof setInterval>
like image 52
Joachim Berdal Haga Avatar answered Oct 22 '22 03:10

Joachim Berdal Haga


The type depends on which function you are going to use there are 2 overloads, the return type is marked in red bounding-box :

enter image description here

In order to use the one which returns number, please use :

window.setInterval(...)
like image 38
Stav Bodik Avatar answered Oct 22 '22 02:10

Stav Bodik


The type is number;

private autoSaveInterval: number = setInterval(() => {
  console.log('123');
}, 5000);
like image 46
user3003238 Avatar answered Oct 22 '22 03:10

user3003238