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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.