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?
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.
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.
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() .
setTimeout and setInterval are the only native functions of the JavaScript to execute code asynchronously.
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>
The type depends on which function you are going to use there are 2 overloads, the return type is marked in red bounding-box :
In order to use the one which returns number, please use :
window.setInterval(...)
The type is number;
private autoSaveInterval: number = setInterval(() => {
console.log('123');
}, 5000);
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