Challenges with the angular timer functions .stop() and .resume()

Having trouble with my timer functionality. It seems I may have over-complicated things, but what I really need is the ability to count from 00:00 to 45:00 and pause and resume the timer within those limits.

Currently, my timer code looks like this:

<timer id="timer" autostart="false" start-time="coutingStart" end-time="countingEnd">{{mminutes}}:{{sseconds}}</timer>

The initialization for countingStart and countingEnd is as follows:

var time = (45 * 60000); 
$scope.countingStart = (new Date()).getTime();
$scope.countingEnd = (new Date()).getTime() + time;

While this code works, a button triggers the timer to start counting from 00:00. However, when pausing and then resuming the timer, there's an issue where time appears to be lost.

Functions for pausing and resuming the timer are in place:

$scope.PauseGame = function() {
    switch ($scope.periodNum) {
        case 1:
            document.getElementById('timer').stop();
            $scope.PauseIsActive = true;
            break;
        case 2:
            document.getElementById('timer').stop();
            $scope.PauseIsActive = true;
            break;
    }
};

$scope.ResumeGame = function() {
    switch ($scope.periodNum) {
        case 1:
            document.getElementById('timer').resume();
            $scope.PauseIsActive = false;
            break;
        case 2:
            document.getElementById('timer').resume();
            $scope.PauseIsActive = false;
            break;
    }
};

Although these functions work, there's an issue with losing time when pausing and resuming at specific intervals.

I suspect the problem lies within how $scope.counterStart and $scope.counterEnd are calculated. How can I ensure accurate timing from 00:00 to 45:00 while maintaining the ability to pause and resume the timer?

The Angular timer utilizes the Date object and milliseconds for time tracking, suggesting a different approach might be necessary to achieve the desired functionality. Any insights on achieving accurate time measurement and control are appreciated.

Thank you.

Answer №1

After reviewing the angular-timer documentation, it is clear that the end-time parameter sets the countdown time without specifying a maximum value.

The end-time parameter establishes the countdown based on a pre-defined end time in milliseconds.

If you want to implement a maximum value for the timer, you can monitor each tick event to check if the configured threshold has been reached. Below is an example where the timer stops when it reaches the maximum value of 10 seconds.

(function() {
  angular
    .module('exampleApp', ['timer'])
    ...

})();
<!DOCTYPE html>
<html ng-app='exampleApp'>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-timer/1.3.4/angular-timer.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/humanize-duration/3.9.1/humanize-duration.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
</head>

<body ng-controller="ExampleController as vm">
  <timer id="timer" autostart="false" interval="1000">{{mminutes}}:{{sseconds}}</timer>
  <button ng-click="vm.startTimer()" ng-disabled="vm.isTimerRunning() || vm.isMaxReached">Start Timer</button>
  <button ng-click="vm.stopTimer()" ng-disabled="vm.isTimerStopped() || vm.isMaxReached">Stop Timer</button>
  <p ng-if="vm.isMaxReached">Max time has been reached</p>
</body>

</html>

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

Using JavaScript AJAX to send a PHP POST request

I am encountering an issue where my data is not being inserted into the database. When I check the console log and network, I receive a blank response. The problem might stem from the fact that my JavaScript source code contains a mix of other stack overfl ...

Tips for holding down a non-modifier key, like the space key, with selenium as a user

I encountered an issue where selenium is unable to press and hold a key that is not included in the list of predefined keys: Keys.SHIFT, Keys.CONTROL, Keys.ALT, Keys.META, Keys.COMMAND, Keys.LEFT_ALT, Keys.LEFT_CONTROL, Keys.LEFT_SHIFT In my application, ...

the buttonclick won't pause the timer

I'm having trouble with the timer function when a button is clicked. The startpause() method sets the start and stop timers, but when I click the button rapidly multiple times, the timer starts to jump by 2-3 seconds. It seems like more than one timer ...

Trigger a function when a button is clicked

This is an ongoing project that includes a calculator and other features. Right now, I am working on a functionality where when you input a number into the calculator results and press "+", it should trigger onClick to check if the input was an integer o ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

Server-side error encountered during a file upload using Ajax

I am attempting to set up ajax file upload using the HTML5 File API, following Afzaal Ahmad Zeeshan's guidance in response to this query. Even though I have replicated the entire code he provided, I am unable to make it function. The primary objecti ...

Encountering an ExpressionChangedAfterItHasBeenCheckedError in Angular 6 when selecting an option from a dropdown menu

How can we fix the error mentioned below through code changes? Situation An input dropdown UI is safeguarded against unintentional value changes by a modal. However, triggering an event (such as click or focus) on the dropdown leads to the ExpressionChan ...

Issue with Angular promise finally clause not executing

I am facing an issue with my RestService where the finally clause is not getting called in the controller method, even after assuming it would be triggered on either success or failure. My current setup involves using angular 1.3.13. var restService = { ...

Comparing response times between AngularJS $http and $.ajax callbacks

I am puzzled as to why AngularJS $http service's success callback is giving me a slower response time compared to the $.ajax success callback. I ran this code 5 times with different JSON files: if(isJquery){ $.ajax({ type : 'GET', ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

Data retrieval on dashboard through ajax is not functioning properly

I have a dashboard with a partial view called SIM Balance. This view is intended to display the number of SIM cards issued to users on a daily basis. I have configured the controller as follows: public function actionSimbalance() { // SQL query to fe ...

html The selection in the dropdown menu is not showing the expected value

When using Firefox version 46.0.1, I encountered an issue with a select element that contains a value attribute being altered by Javascript code. Despite this change being confirmed in the browser inspector window with the select element showing a new valu ...

Testing out a login form in Vue framework

Hi there! I recently put together a login form using the Vue.js framework, and now I'm looking to write some tests for my API calls. Although I'm still new to Vue.js, I'm eager to learn more about testing in this environment. Here's th ...

The resizing of the window does not occur when a scrollbar is automatically added in IE11

I encountered an issue with my Angular project where the view resizes properly in Chrome and Firefox, but not in IE 11. When the scrollbar appears, some components get covered by the scrollbar. Here is the CSS for the menu: #menu-principal .navbar-lower ...

The XML format is not being rendered properly

Every time I try to access , I receive the following error message: This XML file does not seem to have any associated style information. The structure of the document is displayed below. <rss xmlns:media="http://search.yahoo.com/mrss/" version="2.0 ...

Transforming a string into an object

I've been working on this code where my aim is to convert a string into an object and then display the data from an ajax call. However, it appears that using the string value in this way is not functioning as expected. var string = "first: 'Geor ...

When sending an ajax request with HTML data as the payload

While working on an MVC program, I encountered an issue when trying to send data from a TextArea to the controller upon a button click. Everything worked fine until I had HTML-based data inside the TextArea. Here's a snippet of the HTML code: <te ...

DotJem AngularJS routing: Unable to find the 'pagename' within the '$root' directory

Every time I launch the website, everything seems fine at first, but then all the links turn out to be broken. Although they are clickable and lead to the correct URL, the content related to that specific page doesn't appear. Interestingly, if I copy ...

"Troubleshooting: Sub-routes in AngularJS not displaying when directly typing in the

My AngularJS setup is configured to use HTML5 routes and it functions perfectly on urls like website.com/foo. However, I am facing an issue when creating routes for subpages, such as website.com/foo/bar. In this case, the correct page only appears when c ...

How can I stop Javascript from running on a website?

I have come across a question that has been asked previously, and while I found the answer to be helpful (view here: https://it.stackoverflow.com/a/550583), it doesn't quite provide the desired solution. Here's some background information: I am ...