Callback of setTimeout function when performing synchronous actions Inside a function I'm calling playgame service. Once I've obtained the needed data (gameBeingPlayed), I need to show a 3..2..1 counter and then start a game.

chooseGameService.playGame(gameDefinitionID)
                .then(function () {

                    vm.container.gameBeingPlayed = chooseGameService.gameBeingPlayed;

                    showGame();

                    counter(3);  

                });




 function counter(count) {
        vm.container.counterVisible = true;

        var countDownFrom = count;
        var timer = setInterval(function() { handleTimer(count); }, 1000);

        function handleTimer() {
            if(count === 0) {
                clearInterval(timer);
                //
                initGame();
                vm.container.counterVisible = false;
            } else {
                $('#gameCount').text(count);
                count--;
            }
        }           
    }


The things that bothers me is that I had to move the next two lines from the service (promise) callback to the counter in order to execute the code synchronously.

initGame();
vm.container.counterVisible = false;


It works, but it seems semantically wrong for me that initGame() and visibility change is inside the counter function instead of inside the callback of the service (which is inside the controller).

Is there any way I could keep these lines inside the .then() of the controller instead of inside the counter function?
I'd make the counter function return a promise. If you understand promises, I think this example will be enough. If not, please ask and I'll clarify.

function counter(count) {
    var deferred = Promise.defer();

    var countDownFrom = count;
    var timer = setInterval(function() { handleTimer(countDownFrom); }, 1000);

    function handleTimer(count) {
        if (count === 0) {
            clearInterval(timer);
            deferred.resolve();
        } else {
            console.log(count);
            countDownFrom--;
        }
    }

    return deferred.promise;
}

Promise.resolve()
    .then(function() {
        console.log('start');
        return counter(3);
    })
    .then(function() {
        console.log('ready');
    });