Beginning a counter: a step-by-step guide

I am currently utilizing Angular to create a functional counter like so:

<button ng-click="order.startOperation(operation)">
   <p ng-if="counter.start"></p>
</button>

When the button is clicked, it triggers a function that initiates the counter. I have incorporated an ng-if statement to display the minutes and seconds as they tick by once the counter starts running. It's worth noting that this same button can also be used to halt the counter.

function startOperation(operation) {

    var operation.lastStart = Date.now();
        operation.playing = true;

  }

// Pause an operation timer.
function pauseOperation(operation) {
    var operation = vm.data.operations[vm.data.operations.indexOf(operation)];

    if (!operation.start) {
      operation.start = operation.lastStart;
    }

    operation.end = Date.now();

    // Calculate the elapsed seconds.
    operation.partialTime = operation.partialTime || 0;
    operation.partialTime += Math.ceil((operation.end - operation.lastStart) / 1000);
    dataService.update();
}

Answer №1

In order to keep track of time, create a variable called $elapsedTime that will be updated every second:

<button ng-click="order.startOperation(operation)">
    <p ng-if="counter.start">{{$elapsedTime}}</p>
</button>

To update the value of this variable, utilize the $timeout service:

var updateTime = function () {
    $scope.elapsedTime = Date.now() - operation.lastStart;
    if (operation.playing) {
        // continuously update
        $timeout(updateTime, 1000);
    }
}

updateTime();

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

Best practices for creating a factory module in AngularJS

A snippet of a controller function I'm working on: $scope.localTimezone = function (userTimezone,datetime) { // .... return data; } I've been attempting to convert this into a factory module. However, my attempts have resulted in errors. He ...

What is the best way to distribute a function within a div container?

I'm currently working on a function that manages the show/hide functionality and position of tooltips: tooltip = (e) => { // show/hide and position of tooltip // retrieve element data } In addition, I have div elements whe ...

Make sure to remain in the same division area when refreshing the page

Whenever I click the next button and move to step 2, I want the page to stay on the same div even after reloading. The two divs used are join_form_1 and join_form_2 Currently, when I reload the page, it reverts back to the first div. Is there a way to e ...

The standard process and organization of a project using AngularJS in conjunction with Python Flask

As someone new to the MV* client-side framework craze, I find myself leaning towards AngularJS over Knockout, Ember, or Backbone. However, I'm unsure about the workflow involved. Should I start by developing a client-side application in AngularJS and ...

Tips for implementing a conditional statement within an export default clause

I am completely new to web programming and I'm attempting to create a question-answer feature using Vue.js. export default { // Trying to implement an if statement (if character == "Past", then do these steps) "steps": [ { ...

What is the process for programmatically aligning two cards side by side using Material UI in React after retrieving data from an API?

I am currently working with data from an API that I need to display in the format of cards, arranged side by side. To achieve this, I have been using an array and passing the data to components programmatically. You can see the output image and my code bel ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...

Automatically expand accordion on page load using Ionic controller

After successfully implementing the ionic accordion effect using the code provided, everything was working as expected. However, I now have a requirement to automatically open the first accordion by default. <ion-item class="item-stable" ...

Receiving inaccurate video duration when the input bar is modified

Initially, I am uncertain whether the issue stems from Javascript or CSS. The code in question involves displaying the corresponding video time when a user hovers over an input bar. The calculation utilized is as follows: ((user mouseX position / input wi ...

Firefox not responding to mouse movements

I am experimenting with creating an "animation" using JavaScript's "mousemove" Check it out here This is the code I am currently using $("body").mousemove(function(e){ var wWidth = $("body").width()/2 var wHeight = $("body").height()/2 var posX; v ...

Hey there everyone, I was wondering how to send both single and multiple values to a database using JavaScript and JSON endpoints with a Spring Web API

{ "id": 178, "stockin_date": "2022-11-15T08:18:54.252+00:00", "effective_date": null, "expired_date": null, "create_date": null, "update_date&q ...

Load and execute a dynamically created script in JavaScript at the same time

I am exploring the option to load and evaluate a script from a third-party synchronously. Here is an example that currently works well: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

The mapDispatchToProps function is failing to work, throwing an error: Uncaught TypeError: _this.props.addCountdown is not a function

Currently, I am facing an issue while working on my first app. The problem arises with a form component that should send an object via an onSubmit handler. onSubmit = (e) => { e.preventDefault(); this.props.onSubmit({ title: ...

Creating a calculator with JQuery and encountering challenges with performing multiple calculations

I've been working on a calculator using jQuery, but I'm encountering issues with the clear button not functioning properly after multiple calculations. On top of that, subsequent calculations are producing inaccurate results. I am seeking to enh ...

Explore how Vue 2.1 allows for the dynamic updating of dropdown options based on selections made in another dropdown

Currently, I have a Vue v.2 form set up with an address section that includes a State dropdown. My goal is to make the State dropdown automatically populate based on the city selected. For example, if a user chooses 'Atlanta' as the city, 'G ...

The Ajax response is not providing the expected HTML object in jQuery

When converting HTML data from a partial view to $(data), it's not returning the jQuery object I expected: console.log($(data)) -> [#document] Instead, it returns this: console.log($(data)) -> [#text, <meta charset=​"utf-8">​, #text ...

Using JQuery to handle click events on an array of checkboxes and displaying the value of the selected

I am struggling to show the label text and checkbox value from a checkbox array whenever each one is clicked (for testing purposes, assume I want it to appear in an alert). My HTML looks like this: <label class="checkbox"> <input type="checkbox" ...

Timeout set to run indefinitely

Looking at the code snippet below, it seems to be running at a frame rate of 60 frames per second. If any button is clicked, the variable isjump will be set to true and the following code will start executing. The goal here is to exit the jump() function a ...

Attempting to assign a value in ng-init that was only established after loading the model and making two AJAX calls

Let me explain, The project I'm currently working on involves a spinoff of phonegap. I am facing a situation where I need to wait for an AJAX response before setting the ng-init value. Typically, you can set it like this: ng-init = "ng-model = arr[0] ...

Guide to defining a conditional statement in a Nuxt.js application

I am working on displaying data from the Wordpress API in a Nuxt.js project. I am trying to organize the data by category, for example where ('post.category ', '=', 'categoryName '). Can anyone help me with the syntax in Vue.j ...