What is the best way to use AngularJS filters to arrange time?

Currently, I have a timer that is counting down from a user-set value. Users input a number representing minutes, which is then converted to milliseconds by multiplying it by 1000 * 60. The timer then decrements this number as it counts down.

My goal is to display this countdown in the format of minutes and seconds. For example, if a user enters 3.5, it should be displayed as 03:30.

I attempted to use the date filter in Angular to achieve this formatting, but it seems to be out of sync with the timer value. It decrements once and then stops.

Here's the code snippet:

<h4 class="timer">{{ vm.timer.ticks | date: "mm:ss"}}</h4>

The timer functionality is within a service:

start(duration) {
  this.ticks = duration;
  this.timer = this.$interval(() => {
    if (this.ticks === 0) return this.stop();
    this.ticks--;
  }, 1000);
}

Answer №1

It appears the issue might be related to your hidden "this" variable in the inner function. I suggest trying out the following revised code (please note it is untested):

initiateTimer(seconds) {
  let ticks = seconds;
  this.timer = this.$interval(() => {
    if (ticks === 0) return this.endTimer();
    ticks--;
  }, 1000);
}

Answer №2

Oops! I recently realized a major error in my time calculations...

I implemented $scope.$watch to monitor changes in a variable from my service, which in turn affected several other variables.

$scope.$watch('vm.timer.ticks', value => {
  if (value <= 0) {
    vm.timer.count = 0;
    vm.timer.latest = '';
  }
  if(vm.timer.ticks > 0)  {
    seconds = vm.timer.ticks % 60;
    minutes = Math.floor(vm.timer.ticks / 60);
    filledMinutes = minutes < 10 ? "0" + minutes : minutes;
    filledSeconds = seconds < 10 ? "0" + seconds : seconds;
    vm.displayTime = filledMinutes + ':' + filledSeconds;
  } else {
    vm.displayTime = '00:00';
  }
});

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

React - The content of my JSON.String vanishes upon being placed inside a div element

My NFTDetails component includes a description from a JSON, which contains \n\n in it. Strangely, there are no new lines when I render the JSON value in a div, but when I log it to the console in Firefox, new lines appear. How can I make use of ...

Unable to forward with POST request in Node.js

I have a button on the front end that allows users to update their profile photo using the Cloudinary API. When the button is clicked, a Node.js POST request is sent with the user's data to query the database and update the profile photo URL. The func ...

Implement a versatile Bootstrap 5 carousel featuring numerous sliders

Is it possible to create a Bootstrap 5 carousel with six items displaying at a time instead of three? I tried changing the value in the JS code, but it didn't work. Can you correct my code so that it displays six items at a time and can be variable la ...

Tips for customizing plupload to prompt the user for a file title

I have successfully implemented plupload on my website to allow users to upload photos, and I am also using the jQuery queue widget. My current server method only accepts the filename, chunk, and content of the photo. Is there a way for users to specify a ...

finding the node version in a code repository

Is it possible to determine the targeted node version (4 or 6) of a Node.js application by examining its code? I'm currently reviewing this: https://github.com/jorditost/node-postgres-restapi ...

Personalizing Material-UI Components using Styled-Components

My attempt to modify the props of a material-ui Grid component using styled-components was not successful. I initially tried: const NavGrid = styled(Grid)` direction: 'row'; ` Unfortunately, this approach did not yield the desired result. T ...

Is there a way for me to retrieve ruby/rails app variables from an external JS file?

I am currently developing an internal application to monitor the performance of paid search advertising. Imagine I have several paid search campaigns directing traffic to different websites (referred to as "target sites"). When a user clicks on a paid ad ...

When working in Node, leverage the `then()` method to execute functions sequentially

Is there a way to run a loop function synchronously rather than asynchronously without using callbacks or external libraries? File 1 var db = require('./promiseUnderStanding'); var fun = function () { for (var i = 0; i < 10; i++) { ...

Pause and check for the completion of data loading in mapstate

I have a stored userProfile in the Vuex state in order to access it throughout my project. However, when I try to use it in the created() hook, the profile is not loaded yet during the initial page load. Although the object exists, it does not contain any ...

Display some results at the conclusion of eslint processing

As I develop a custom eslint plugin, I am intricately analyzing every MemberExpression to gather important data. Once all the expressions have been processed, I want to present a summary based on this data. Is there a specific event in eslint, such as "a ...

Dividing CSV Data into Two File Outputs

I've got a CSV file that's structured like this: Docushare Host locale, created_at, version en,Wed Feb 21 17:25:36 UTC 2018,07.00.00.C1.609 User handle, client_data, docCountQuota User-12,,-2 Document handle,client_data,cfSpecialWords Document ...

The Chart.js graph fails to appear when placed within an ngIf directive

I have encountered an issue with my simple scatter line chart created using Chart.js within a bootstrap panel. It works perfectly fine until I place it inside an ngIf div. Has anyone faced this problem before? Is there a solution to make the chart display ...

Performance of Nested Menus: A Technological Perspective

In an effort to condense a long stay, the marketing team is requesting our entire sitemap of 5000 pages be accessible through one menu. Despite a year of resistance, we have come to accept that this is inevitable and are now exploring potential technologie ...

React-Redux Error: The function this.props.AppendCharacter is not defined

I have been looking for a solution to my issue but couldn't find anything that matches it. I am working on creating a calculator app using React & Redux, and whenever I click on one of the number buttons, I receive an error message saying "this.props. ...

PHP failed to respond to the AJAX request

Currently, I am in the process of developing a straightforward signup page that utilizes jQuery and PHP with AJAX functionality. The following script is responsible for initiating the ajax call: <script> function submitForm(){ var data1=$( ...

How to customize the appearance of a specific column in Ag-Grid using AngularJs

Is there a way to style a column in ag-grid using AngularJs? I am looking to make it resemble hyperlinks, possibly with different colors for visited and unvisited links. The specific style isn't crucial; I simply want to learn how to style a column. S ...

I keep running into an issue whenever I attempt to import material ui icons and core - a frustrating error message pops up stating that the module cannot be found

[I keep encountering this error message when attempting to utilize @material-ui/core and icons] `import React from "react"; import "./Sidebar.CSS"; import SearchIcon from "@material-ui/icons/Search"; const Sidebar = () => { return ( <> ...

Unable to activate the WebRTC track event

As a novice in the realm of WebRTC, I ventured into creating peer connections between two browser windows. Utilizing a simple WebSocket server in Node.js running locally, everything seemed to be in order until the process of exchanging candidates. Unfortun ...

What is the best way to establish anchors for *ngFor elements in Angular 2 and beyond?

I have a component that displays items using *ngFor. My goal is to scroll down to the element with anchor #3. Here's the code snippet: @Component({ selector: 'my-app', template: ` <button (click)="scroll(3)">scroll 2</butt ...

Sass: Setting a maximum width relative to the parent element's width

I have a resizable container with two buttons inside, one of which has dynamic text. Within my scss file, I am aiming to implement a condition where if the width of the container is less than 200, then the max width of the dynamic button should be 135px, ...