0

I am just a beginner so don't judge me.

I have seen lot of angularjs plugins (directives/services) that uses $timeout function without any time (or time = 1ms).

For example :

scope.openGallery = function (i) {
    if (typeof i !== undefined) {
        scope.index = i;
        showImage(scope.index);
    }
    scope.opened = true;
    document.body.style.overflow = 'hidden';
    /////*******Here*******/////
    $timeout(function() {
        var calculatedWidth = calculateThumbsWidth();
        scope.thumbs_width = calculatedWidth.width;
        $thumbnails.css({ width: calculatedWidth.width + 'px' });
        $thumbwrapper.css({ width: calculatedWidth.visible_width + 'px' });
        smartScroll(scope.index);
    });
};

Any specific reason why they do it or benefits of doing it?

3 Answers3

1

It bumps the functionality off the main display thread (or, as close as you have to a "thread" in javascript).

If the functionality it encapsulates is long-running, it will mean the browser does not become unresponsive.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

It waits for the current digest cycle to finish before executing the callback. This can be useful if certain side effects of other functions dependent on the digest cycle need to be present in order for a particular piece of code to work correctly.

For example, suppose the code above the $timeout() sets a variable that is being $watch()ed by a controller, and the controller performs some other logic and sets some variables, and the code inside the $timeout() needs those variables to be updated for it to work correctly. Good Angular devs try to avoid this situation, but it comes up anyway and $timeout() is the best way to handle it.

Isaac Lyman
  • 2,175
  • 1
  • 22
  • 42
0

Perhaps You Should have taken a look at this answer first. it explains functionality of $timeout very clearly.

$timeout in angularjs

Also It wraps your callback for you automatically in a try/catch block and let's you handle errors in the $exceptionHandler service.

It returns a promise and thus tends to interoperate better with other promise-based code than the traditional callback approach. When your callback returns, the value returned is used to resolved the promise.

Community
  • 1
  • 1
Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131