Explore the various timer functionalities available in Angular.js

I am working on a project that requires displaying two timers on a webpage, each with different start times.

The first timer should only show for 5 seconds, and then after 10 seconds, the second timer should be displayed. I am new to Angular and have written the following code to achieve this functionality.

Everything seems to be functioning properly except when the setTimeout function is called for the third time, it starts running very fast.

Here is the controller code:

// initialize variables
$scope.tickInterval = 1000; //ms
var min ='';
var sec ='';

$scope.ti = 0;
$scope.startTimer1 = function() {
    $scope.ti++;
    min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
    sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
    $scope.timer1 =  min + ":" + sec;
    mytimeout1 = $timeout($scope.startTimer1, $scope.tickInterval); // reset the timer
}

//start timer 1
$scope.startTimer1();

$scope.$watch('timer1',function(){

    if($scope.timer1 !=undefined){
        if($scope.timer1 =='00:05'){
            $timeout.cancel(mytimeout1);
            setInterval(function(){

                $scope.startTimer2()
                $scope.ti = 0;

            },1000)
        }
    }

})

//start timer 2 after 2 minutes and 20 seconds
$scope.startTimer2 = function() {
    $scope.ti++;
    min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
    sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
    $scope.timer2 =  min + ":" + sec;
    mytimeout2 = $timeout($scope.startTimer2, $scope.tickInterval);
}


$scope.$watch('timer2',function(){

    if($scope.timer2 !=undefined){
        if($scope.timer2 =='00:05'){

            $timeout.cancel(mytimeout2);

            setInterval(function(){

                $scope.startTimer1();
                $scope.ti = 0;

            },1000)


        }
    }

})

In my view, I simply have:

<p>{{timer1}}</p>

<p>{{timer2}}</p>

Answer №1

You can simplify your code by using the $interval function instead of multiple startTimer functions. By utilizing $interval, you can effectively handle the timer logic without the need for additional watchers and timeouts in your application.

$scope.Timer = $interval(function () {
  ++$scope.tickCount

  if ($scope.tickCount <= 5) {
    $scope.timer1++
  } else {
    $scope.timer2++
    if ($scope.tickCount >= 10)
        $scope.tickCount = 0;
   }
}, 1000);

Check out this working example on JSFiddle.

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

Ensuring the accurate promise is delivered in Angular

I'm struggling to correctly return the promise for a service in Angular. Here is the function causing me trouble: postToSP.post($scope.sharePointURL, data).then(function() { $scope.gettingData = false; $scope.yammerListName = ...

Resizing Elements with JQuery and Moving Them Forward

I have successfully made multiple objects draggable and resizable using the JQuery plugins for Draggable and Resizable. While dragging an object, it automatically comes to the front due to the stack option. However, when resizing an element without draggin ...

In the world of web development with JavaScript, jQuery, and EasyUI, we often encounter situations where the parameter

function formatData_original() { // convert obj_num2.formatter = function(value, rec) { var baseStr='&nbsp;&nbsp;' + rec.s_date + '<a class="easyui-linkbutton" href="javascript:void(0);" plain= ...

Angular UI Bootstrap Typeahead - Apply a class when the element is added to the document body

In my current project, I am utilizing angular bootstrap typeahead with multiple instances. Some of these instances are directly appended to the body using the "typeahead-append-to-body" option. Now, I have a specific instance where I need to customize the ...

What is the process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into thes ...

Is it possible to customize the pagination-control labels from numbers (1 2 3) to different values, such as 'Anything1 Anything2 ...', by utilizing ngFor* with an array in ngx-pagination?

Is there a way to customize ngx-pagination's pagination control? Currently, the page numbers are displayed as '1 2 3' but I would like to replace them with specific string values from an array. <pagination-controls (pageChange)=& ...

I am unable to display my JSON data in Next.js using a fetch request

I'm having trouble understanding the code, and it seems like the API is open to anyone since it's just a simple JSON. However, I keep getting an error: Error Message: Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit th ...

Problem with Jquery show/hide feature only resolved after refreshing the page

I built a checkout page that consists of three fieldsets with unique IDs - 1, 2, and 3. I want the page to initially display only fieldset 1 while hiding fieldsets 2 and 3. Here is the jQuery code I used: $(document).ready(function(){ $("#1").show(); ...

Ways to deactivate the Bootstrap collapse feature

In my accordion FAQs, I am facing an issue where Question 1 is automatically opened when the page loads. Additionally, when I click on Question 2, it closes instead of staying open. I would like to address these problems and make sure that each question st ...

Incorporating dynamic numerical values into image names within a Vue JS application

I have linked an image with the following code <img title="head" :src="availableParts.heads[selectNextHeadIndex].src"/> This image is called from a JSON file: { id: 1, description: 'A robot head with an ...

Can you identify the issue with my database file?

Here is the content from my database.js file: const MongoClient = require('mongodb').MongoClient; const db = function(){ return MongoClient.connect('mongodb://localhost:27017/users', (err, database) => { if (err) return co ...

What is the proper way to confirm the authenticity of a captcha code

hey there, I'm struggling with my captcha code. The issue is that it still accepts wrong captchas when entered in the input box. Can someone guide me on how to validate the wrong captcha entry? Here's my form code: <p class="Captcha" style=" ...

Testing the equality of nested arrays: A step-by-step guide

My maze generator creates walls for each "cell", resulting in duplicate walls - such as the left wall of one cell being identical to the right wall of the adjacent cell. I have managed to convert the maze data into a different program where it is stored in ...

Pass a customized field as an argument to the .find() method in mongoose

When making an HTTP call to my api to fetch documents from a mongodb, I include two parameters in the URL: campo and keyphrase. My goal is to retrieve all documents where the parameter campo is set to my specified keyphrase. For example, if I have some doc ...

What is the most popular method for namespacing AngularJS modules?

I am new to AngularJS and currently exploring different ways to namespace modules in my application. One challenge I face is the need to integrate my Angular app into a designated placeholder div within a third-party website (which may also use Angular), ...

Encountered an error while trying to install @material-ui/core through npm: Received an unexpected end of JSON input

npm install @material-ui/core npm ERR! Unexpected end of JSON input while parsing near '...X1F+dSMvv9bUwJSg+lOUX' npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\WR-022\AppData\Roaming\npm-cach ...

Generating a dynamic list by utilizing database data once a button has been clicked

I'm looking to create a feature on my website where clicking on a button will populate a paragraph below it with data retrieved from a database query containing two columns. The first column provides the text for a list, while the second column contai ...

Interactive data table feature in React, transferring selected row data to a modal pop-up

I am currently developing an offline Progressive Web App (PWA) using ReactJS and have integrated the react-data-table-component, which has been very helpful so far. Within the table, I have implemented an onRowClicked function that triggers whenever a row ...

Using Jquery to find the class that matches the current element

Is it possible to select a specific div by its class when there are multiple divs sharing the same class and triggering the same function on button click? I only want to target the class where $(this) is located. I've experimented with .parent, .chil ...

Populate DataTable with HTML content by fetching it through Ajax requests

My goal is to dynamically load the HTML returned from a controller into a div when a user clicks on a row in a table. Check out my code snippet below: // Add event listener for opening and closing details jQuery('#exRowTable tbody').on ...