0

So is there any possibility to reach .then() only after $scope.counter reaches 5?

Here is JSFiddle

Somehow using Promise ruins my watcher - it applies only when window gets resized. So i would like to know if i could do it without Promises

<div ng-app="myApp">
    <div ng-controller="myController">
    <div>some{{message}}</div>
    <div>counter: {{counter}} sec</div>
    </div>
</div>

(function(){

var myApp = angular.module('myApp', []);

myApp.controller('myController', function($scope, $timeout){

    //time
    $scope.counter = 0;
    $scope.message = "";

    //timer callback
    var timer = function() {
        $scope.counter++;
        if ($scope.counter > 5) {
            return;
        }
        $timeout(timer, 1000);
    }

    $timeout(timer, 2000).then(function() {
        $scope.message="body once told the world was gonna roll me";
    });       

});

})();

1 Answer 1

1

$timeout doesn't return any sort of Promise however, if you really want to have this work off of promises, you can do the following:

var defer = $q.defer();
var timer = function() {
    $scope.counter++;
    if ($scope.counter > 5) {
        defer.resolve(true);
        return;
    }
    $timeout(timer, 1000);
}

$timeout(timer, 2000);
defer.promise.then(function() {
    $scope.message="body once told the world was gonna roll me";
});   

Plunker: https://jsfiddle.net/463srkyj/

Without knowing more about your code, I'd suggest perhaps using an $interval instead of $timeout if both timeout values can be the same. Also would ask why not just set your message inside your if ($scope.counter > 5) condition.

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

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.