Where developers come to connect, share, build and be inspired.

116

AngularJS: use $timeout, not setTimeout

33201 views

There are some cases where one needs to perform some sort of timeout operation and we frequently achieve this using JavaScript's setTimeout() function.

However, if we use setTimeout() in an AngularJS application we also need to use $scope.$apply() to ensure that any changes to the scope will be reflected elsewhere (i.e. data-bound in a view).

AngularJS provides a handy wrapper for this: $timeout() - it does the $apply() call for us so we don't have to. Magic!

function Ctrl($scope, $timeout) {
    $scope.timeInMs = 0;

    var countUp = function() {
        $scope.timeInMs+= 500;
        $timeout(countUp, 500);
    }

    $timeout(countUp, 500);
}

And here's a JsFiddle showing it working: http://jsfiddle.net/otupman/fq4vg/

Update and warning- if you're using $timeout to create what is essentially an interval; don't - it will break your e2e tests :( The workaround is to set the standard setTimeout for the moment :( :( :(

More info on the Angular github issue here: https://github.com/angular/angular.js/issues/2402

Comments

  • 2013-4-6-prof
    dparnane

    $timeout is really handy indeed! I'd also like to see $interval alongside $timeout.

  • Blank-mugshot
    otupman

    Agreed! If I get the chance I might look into that, though I do think someone else must have written one.... maybe :D

  • 2013-4-6-prof
    dparnane

    @otupman Yeah, all kinds of hackish workarounds can be spotted out there in the wild: http://stackoverflow.com/a/14238039/1809349

  • Dan_100_normal
    dankapusta

    Oh wow, I just posted a similar tip after suffering thru a setTimeout() issue for a while on Friday. Wish I had seen this tip on Thursday :D

  • Blank-mugshot
    mattstyles

    Yeah there are a couple of $interval implementations kicking around, with various degrees of success.

    Hoepfully it'll be standard soon.

  • Blank-mugshot
    faceleg

    Great tip!

  • Me
    davidchase03

    As of 1.2 they will have $interval :)

Add a comment