AngularJS countdown button

I have developed a unique countdown feature that only runs when the user is actively using the browser window. It works perfectly, but I am facing an issue when integrating this code into an AngularJS controller. I have included my code below for reference.

JavaScript:

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>

Answer №1

Avoid using non-angular functions such as setTimeout or setInterval within your angular code as they will not be included in the digest cycle, causing your view to remain static.

Refer to this example on how to create a timer using angular:

https://examplewebsite.com/angular-timer-example/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for receiving the "Must provide query string" error when using the fetch API, but not when using cURL or Postman?

I've been attempting to integrate the graphbrainz library into a React app using the fetch API. No matter how I structure my request body, I keep encountering this error: BadRequestError: Must provide query string. at graphqlMiddleware (C:\U ...

What is the reason behind allowing JavaScript to perform mathematical operations with a string type number?

let firstNum = 10; let secondNum = "10"; console.log(firstNum * secondNum); // Result: 100 console.log(secondNum * secondNum); // Result: 100 ...

Switching buttons with AngularJS

I am currently working on a Github search app using the Github API in Angular. My goal is to make it so that when the user clicks the "Add to Favorite" button, the button disappears and the "Remove Favorite" button is displayed instead. I attempted to achi ...

I could use some assistance in grasping the nuances of creating a Vue instance and determining the best practices for doing so. Can you explain when each option is

I've been pondering the preferred and best practice method for creating a Vue instance in main.js. When starting a new project using the CLI, the instance is created like this: new Vue({ render: h => h(App) }).$mount("#app"); However, the docume ...

Issues have been raised with IE11's refusal to accept string(variable) as a parameter for the localStorage

Why is it that Internet Explorer does not recognize a string variable as a parameter for the setItem method, even though it works fine in Chrome? For example, in IE: This code snippet works: var itemName = 'anyname'; localStorage.setItem(itemN ...

What is the best way to add attachments to the clipboard in a Chrome extension?

One possible way to achieve this is by using the navigator.clipboard.write API, but keep in mind that this API is not available to background pages of Chrome extensions. A method I attempted involved creating a blob like this: let blobFinal = null; // ...

Utilizing Q for Node.js promise handling

I am currently working on a Node application where I need to utilize promises for handling asynchronous calls. Although I have a foreach loop inside a .then(function()) of a promise, I am facing an issue where I am unable to return the final result of the ...

Refreshing ng-options upon modification of a scope variable

Why is my selectbox not refreshing with ng-options when the scope variable is updated by an HTTP request in the controller? Is there a way to force the selectbox options to refresh on the UI? In my case, I am loading selectbox options from a database (loo ...

Sending ID via http.get request in Ionic using AngularJS

Can anyone help me figure out why I can't pass the session_id to my http.get function? This is what my controller looks like: .controller('feedCtrl', function($scope,$rootScope,$ionicHistory,$state,$http) { $scope.session_id= sessio ...

ng-class expressions are constantly evolving and adapting

Within a div, I am utilizing ng-class="{minifyClass: minifyCheck}". In the controller, I monitor changes in two parameters - $window.outerHeight and $('#eventModal > .modal-dialog').height(). If there are any changes, I trigger the minifyChan ...

Issue: [$resource:badcfg] There was a problem in configuring the resource for the `query` action. The expected response should have been an array, but an

As a newcomer to MEAN stack development, I just started yesterday and am encountering an issue when trying to retrieve data from the database using a resource linked to a server-side controller. The console displays this error message: "Error: [$resource:b ...

Is there a way to point my Github URL to the index file within a specific folder?

The actual working location of my website: My desired working location for the site: Originally, I had my index.html file in the main repository, but later moved it to an html folder along with other html files for better organization. How can I ensure t ...

Add a parameter within a loop using JavaScript

I am currently working on a function with a parameter called menu. removeChildCheck:function(menu){ let removeArrayValues = []; for(var i=0; i < this.checkbox.menu.length; i++){ removeArrayValues.push(this.checkbox.menu[i].value); ...

Having trouble with the postcss-import grunt plugin?

Here is the layout of my project: my_project |-- css | -- main.css |-- css-dev | -- main.css |-- node_modules | -- bootstrap | -- dist | -- css | -- bootstrap.css |-- package.json `-- Gruntfile.js The contents of my Gr ...

Looping through a set of API calls using JavaScript Web API

Currently, I am in the process of developing an application using angularjs and ionic. Within this app, I have an array containing IDs, and my objective is to retrieve their corresponding names. To achieve this, I attempted the following code snippet: var ...

Ideal location to detect web browser and display or conceal a division

I am looking to display a div using either the ng-if or ng-show/hide directives if the user accesses the page through a specific browser, such as Chrome/Chromium. However, I am unsure of the optimal location to place this functionality. The JavaScript cod ...

Combining NPM Script Commands: A Comprehensive Guide

I am aware that NPM scripts can be chained using &&, pre-, and post- hooks. However, I am wondering if there is a way to simply break down lengthy script lines into a single, concatenated line? For instance, can I convert the following: "script": ...

Using Buttons to Filter Data in React

My goal is to implement button functionality that filters data from a JSON file. Upon clicking a button, the state should be updated with the filtered JSON data and display the list with the updated information. Currently, I have four buttons for filteri ...

Achieving compatibility between Select2 Gem and ActiveAdmin "New" Button

I have a Ruby on Rails application that utilizes the ActiveAdmin and Select2 Gems. Currently, I have implemented a search box that displays potential options from the provided set after typing two letters. The code for this feature is as follows: f.has_ma ...

The output display is not visible

I am currently working on a tutorial to showcase contact details on my webpage. However, I am facing an issue where the code is not displaying the first and last name as expected. Below is the code snippet for reference. Snippet from index.html <!DOCT ...