Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS $timeout vs $interval

Tags:

angularjs

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.

like image 509
Mawg says reinstate Monica Avatar asked Apr 16 '14 09:04

Mawg says reinstate Monica


People also ask

What is $timeout in AngularJS?

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.

What is $interval in AngularJS?

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.

What is the difference between $timeout and setTimeout?

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 $.

What is the function of $Timeout service?

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.


2 Answers

$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.

like image 166
Kemal Fadillah Avatar answered Oct 16 '22 22:10

Kemal Fadillah


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.

like image 3
Batandwa Avatar answered Oct 16 '22 23:10

Batandwa