Utilizing a timer in AngularJS to enumerate through an array of integers

Exploring the functionality of $timer in angularjs for countdowns has been an interesting journey. While resources are abundant for creating basic count up or countdown timers like this example, my current challenge is looping through an array of integers to countdown each one individually to 0.

Here's a snippet of my HTML code:

<!doctype html>
<html ng-app>
... (omitted for brevity)
</html>

And here's my JavaScript code:

function AlbumCtrl($scope,$timeout) {
    $scope.counterArray = [5,10,15];
    $scope.onTimeout = function(){
      for(var i = 0; i < counterArray.length; i++){
        $scope.counterArray[i]--;
        if ($scope.counter > 0) {
            mytimeout = $timeout($scope.onTimeout,1000);
        }
      }
    }
    var mytimeout = $timeout($scope.onTimeout,1000);          
}

The goal is to display a countdown from 5 to 0, then 10 to 0, and finally 15 to 0 at 1-second intervals. Even after tweaking the jsfiddle example and incorporating an integer array and loop, I'm facing some challenges.

JSBin link: http://jsbin.com/vaqene/1/edit

If you have any suggestions on how to tackle this issue, your insights would be much appreciated!

Answer №1

Give this code a try, it should meet your requirements.

function AlbumController($scope, $timeout) {
    $scope.numbersArray = [8, 16, 24];
    $scope.number = 8;

    $scope.currentIndex = 0;

    $scope.updateNumber = function() {
        $scope.number = --$scope.numbersArray[$scope.currentIndex];

        if ($scope.numbersArray[$scope.currentIndex] === 0 && $scope.currentIndex < 3) {
            $scope.currentIndex++;         
        }

        $timeout($scope.updateNumber, 1000);
    };

    $timeout($scope.updateNumber, 1000);
}

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

Tips for displaying images uploaded by the user in a div using an input field

I have a file input field where users can select a file to upload. I want to use JavaScript to display the selected file after it has been uploaded by the user. How can I accomplish this? Does anyone know how to show the selected file in a file input fiel ...

How can I optimize Javascript and CSS that are being used on my website but are not physically hosted on my website?

On my website, I have a plugin called "Contact Us" that was created and is being operated by Dropifi. Lately, I've been working on optimizing my site for SEO/Speed using Google's PageSpeed Insights tool. I enabled compression with GZip for all el ...

After the array is printed, the foreach loop is failing to function as expected

I attempted to loop through the given array. Array ( [mech_info] => Array ( [make] => Amaka [0] => Array ( [year] => 2001 [model] => Array ...

NodeJs: Issue with executing Mongodb query within a cron job using node-cron

I set up a cron job to perform database updates, but for some reason, the query doesn't seem to be executing. Here is the code for my cron job: const cron = require('node-cron'); const Document = require('../models/document&apo ...

Issue encountered while assigning values to a deeply nested object

Issue with setting values in a nested object I am trying to insert data into the following object structure. Company { stat { internalData { value = 35 } } } This is the code I have used: Company.stat.internalData[" ...

Having trouble initiating an AJAX call in Django and returning values to my form

Seeking assistance to run an AJAX call for a quick calculation in my django view and display the result within a span tag on my HTML page. New to Javascript, struggling with triggering my AJAX call. Below is my HTML and JS code: <input type="text" nam ...

Begin the directive once the API has been completed

My dilemma lies in a directive whose data relies on the API response. The issue is that the $compile of the directive occurs before the API is fully processed, resulting in an incorrect state for the directive. Is there a way to address this problem? Is t ...

Laravel: Structuring query results with nested joins into a sub array

IMPORTANT Please refrain from recommending the use of Eloquent, as we are specifically focusing on utilizing the Laravel query builder. Due to performance considerations, we have opted to retrieve results from a table using Query Builder: DB::table(&apos ...

Issue with THREE.SpriteCanvasMaterial functionality

This unique piece of code (inspired by this and this example): generateCircle = (ctx) -> position = 0.5 radius = 0.5 ctx.scale(0.05, -0.05) ctx.beginPath() ctx.arc(position, position, radius, 0, 2*Math.PI, fa ...

Steps for setting up type-graphql in your projectNeed help with

Trying to include this in my TypeScript project: import { ID } from "type-graphql"; Encountered an issue when attempting to install type-graphql. Received a 404 error stating that it could not be found in the npm registry. npm install @types/type-graphq ...

Access the second argument in the method `document.getElementById("box5" && "box14")`

I need help with a script that should set the variable trouve_coupable to true only if both box 5 and box 14 are checked on my HTML page. However, no matter what I do on the page, whenever box 14 (="case14") is checked, it always returns true whe ...

Discover the position of the element that was clicked within the group of elements sharing the

Here is my HTML code: <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value="X"> <input type="button" class="buttonclose marleft fleft clrPric" value= ...

Exclude weekends from DateTime

Currently working on a task list and aiming to set the default date to 3 days from now, excluding weekends. Utilizing Vue and thinking a computed property might be the solution? DateTime.utc().plus({ days: 3 }).toFormat('yyyy-MM-dd HH:mm:ss'), ...

Stop users from swiping down on Lockscreen/Notification Center in a react-native app

With the release of iOS 11, there was a change in how the system prioritizes gestures on screen edges versus user-defined gestures. Previously, when the status bar was hidden, iOS would give priority to custom gestures on screen edges. Now, in order to ac ...

Creating an if statement based on the currently chosen option

My angular JS page includes a drop-down list: <div class="col-md-4 fieldMargin"> <div class="dropdownIcon"> <select name="actions" id="actions" ...

The Bootstrap modal stubbornly refuses to close even after resetting the HTML body

I am having an issue with my bootstrap modal where the closeModal button is not functioning properly after the printModal button has been clicked. The modal does not close as expected. Step 1: Click on the printModal button after the modal pops up (this w ...

Internet Explorer's textarea slows down when used after a large table list

I've been tasked with developing an ecommerce site for my employer that allows users to order articles. After displaying a long list of articles, I noticed that entering comments in the textarea below becomes very slow. This issue only occurs when dea ...

Is there a way to minimize the use of .value in Vue 3?

After recently diving into Vue 3, I find myself struggling to grasp some key concepts of the composition API. My current challenge involves converting a library from Vue 2 to Vue 3, where a reactive property named layout is being passed down to child compo ...

Reverse the order of columns in a CSV file

Currently, I am importing a csv file into MaxMSP and running it through a javascript object. The process involves the following steps: 1) Removing the header line from the file 2) Transforming the csv file into an array 3) Converting elements from the arr ...

The recursive function continues to output a negative result

I'm struggling to understand why my recursive function keeps returning false instead of true. const location = { name: "917", parentLocationCluster: { name: "Key Zones" ParentLocationCluster: { name: "Bla" } } } cons ...