1

i created a countdown feature where it only counts if the user is in the current window of the browser, and it works very well, the only problem is when i insert my code in angularjs controller. It stops working, above i leave my code to everybody have a idea what is wrong.

js:

var span = angular.element('#count');
        var counter = 30;
        var timer;

        var startTimer = function() {
            // do nothing if timer is already running
            if (timer) return;

            timer = setInterval(function() {
                counter--;
                if (counter >= 0) {
                    span.innerHTML = counter;
                }
                // Display 'counter' wherever you want to display it.
                if (counter === 0) {
                    alert('this is where it happens');
                    stopTimer();
                }
            }, 1000);
        };

        var stopTimer = function() {
            clearInterval(timer);
            timer = null;
        };

        var onBlur = function() {
            stopTimer();
        };

        var onFocus = function() {
            startTimer();
        };

        var onLoad = function() {
            startTimer();
        };


        angular.element(window).load(onLoad);
        angular.element(window).blur(onBlur);
        angular.element(window).focus(onFocus);

html:

<a  class="btn btn-medium btn-orange" href="">
            In<span id="count">30</span></a>
1
  • Do use $interval instead of setInterval, which will take care of digest cycle to keep binding in sync & then use $interval.cancel(interval) to clearInterval, Additionally angular.element('#count') should be angular.element(document.getElementById('count')) as jQLite doesn't support selector based query Commented Apr 22, 2016 at 14:31

1 Answer 1

2

Don't use non angular functions like setTimeout or setInterval inside angular code. These functions won't be part of the digest cycle and your view won't change.

Take a look at this example for creating a timer with angular.

https://codeforgeek.com/2014/09/refresh-div-angularjs-interval/

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

1 Comment

hi, this link is broken

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.