What's the difference? When should I use which? I am new to Angular & they look very similar to me. I would rather follow best practices from the start.
This '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
AngularJS includes $interval service which performs the same task as setInterval() method in JavaScript. The $interval is a wrapper for setInterval() method, so that it will be easy to override, remove or mocked for testing. The $interval service executes the specified function on every specified milliseconds duration.
setTimeout in order to display an alert message after a timeout of at least 2000 milliseconds. Angular $timeout is a wrapper written for window. setTimeout in form of a try catch block which throws exceptions via $exceptionHandler service. $timeout accepts the function to be delayed, delay time, a boolean to invoke $.
The $timeout service can be used to call another JavaScript function after a given time delay. The $timeout service only schedules a single call to the function. For repeated calling of a function, see $interval later in this text.
$interval
executes a callback repeatedly, while $timeout
simply delays the execution of a callback (doesn't repeat). So, no, they're not the same. Additionally, it should be noted that both of them are wrappers for window.setInterval
and window.setTimeout
respectively.
I would also like to recommend to read this great article written by John Resig on how Javascript timers work.
Here's some info extracted from djvirgen's response to a similar Reddit question:
You should always be using $timeout in Angular apps. Here's why:
- It's injectable, making testing easier with ngMock.
- It runs a digest to ensure your view is updated.
- It is thenable (it's also a promise).
However, if you don't want a digest to run, you can simply pass false as the third argument.
I would guess $interval has similar advantages.
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