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

Coat the div with a uniform shade of pure white

I need assistance on applying a solid white background color to hide the text behind it. For better understanding, I have attached a screenshot as a reference. https://i.stack.imgur.com/f8Qd9.png The issue arises when I click on the dropdown in the heade ...

Combining a 3D array into a 2D array with the addition of HTML tags around each value using JavaScript

3D array // Array var x = { "letter": [ "a", "b", "c", "d", "e", "f", "g", "h", "i" ], "line": [ { "data": [ 306, 830, 377, 651, 547, 369, 300, 148, 494 ] }, { "data": [ 88, 339, 298, 87, 96, 108, 93, 182, 64 ] }, { "data": [ 3157, 2943, ...

"Classes can be successfully imported in a console environment, however, they encounter issues when

Running main.js in the console using node works perfectly fine for me. However, when I attempt to run it through a browser by implementing an HTML file, I do not see anything printed to the console. Interestingly, if I remove any mentions of Vector.ts fro ...

What is the most effective method for implementing the angular ng-app in your project?

As a beginner in Angular, I am wondering whether it is better to have one ng-app for the entire website or use multiple ng-app directives for individual pages? ...

Let's update the VUE app's development server to point to my-testing-web-address.com instead of the default localhost:

I am working on a VUE application and I am trying to run it on an external link instead of localhost. I attempted to configure a vue.config.js devServer: { host: 'http://my-testing-web-address.com', port: 8080, ... } and adjusted t ...

Combine all div elements to create a unified image and then proceed to save it as a jpg file before uploading to the server

These are the divs below: <div style="width:800px; height:420px; position:absolute; top:0px; left:0px; z-index:10; background-image: url('https://3t27ch3qjjn74dw66o1as187-wpengine.netdna-ssl.com/wp-content/uploads/2016/05/052516-800x420-vege-Wallp ...

Using jQuery to adjust the length of a string to fit within a specific width

I am working with a table and need to input strings in each cell, but they are wider than the cell width. I want to shorten the strings without breaking lines, and add '...' at the end to show that the string is long. The table consists of aroun ...

Using the `await` command may lead to the variable losing its scope

Utilizing the await keyword to retrieve data from the database has been causing me some trouble. The variable secuity_ok is set to true on one line, but inexplicably changes to false on the following line. What could be causing this issue? It's worth ...

Choosing a request date that falls within a specified range of dates in PHP Laravel

In my database, I currently store two dates: depart_date and return_date. When a user is filling out a form on the view blade, they need to select an accident_date that falls between depart_date and return_date. Therefore, before submitting the form, it ne ...

Adjust the width of a container to exceed 32767 using jquery in the Opera browser

I am looking to create a compact timeline using jQuery, and I want this timeline to have a width exceeding 32767 pixels. Interestingly, when I attempt to modify the width using the jQuery code $(".timelinecontainer").width(32767);, it doesn't seem to ...

What methods can be used to prevent accessing 'res' after the resolution of getServerSideProps?

While working on my nextJS application, I encountered an error in the page file: warn - You should not access 'res' after getServerSideProps resolves. Read more: https://nextjs.org/docs/messages/gssp-no-mutating-res I tried reading the provided ...

Looking for assistance with ReactJs code related to implementing a filter button

I've been working on creating a filter button using ReactJs, but I can't seem to get it to work properly. I've spent a lot of time troubleshooting, but the issue persists. You can view my codePen here: https://codepen.io/tinproht123/pen/gOxe ...

Utilizing AngularJS to Extract JSON Data from Gzipped Files Stored Locally via Ajax

Currently, I am attempting to retrieve and read a JSON file that is stored in data.gz using AngularJS's $http service. However, when I make the request, all I get back are strange symbols and characters as the response. My application is being run loc ...

Limiting the size of images within a specific section using CSS

When using CSS, I know how to resize images with the code snippets below: img {width:100%; height: auto; } img {max-width: 600px} While this method works effectively, it applies to every image on the page. What I really need is for some images to be ...

Converting objects into JSON format

I'm trying to transform an object that looks like this: { user[id]: 1, user[name]: 'Lorem', money: '15.00' } Into the following structure: { user: { id: 1, name: 'Lorem', }, money: ...

Tips for designing a sleek and seamless floating button

I attempted to implement a floating button feature that remains in view while smoothly flowing using jQuery. I followed a tutorial I found online to create this for my website. The tutorial can be accessed at this link. However, after following all the ste ...

Encountering an error when trying to access a property of an undefined MVC model in a

Embarked on a journey to learn web service development, only to encounter a roadblock. I'm struggling to figure out how to utilize ExpressJS Router() to pass POST data to the controller files. Upon inspecting the request redirected from product.route. ...

Measure the loading times of external web pages using JavaScript

I am seeking a minimalist approach to create a webpage on my server that utilizes JavaScript to calculate the loading time of the login page on various remote URLs/servers. These servers are dispersed globally, and my aim is to determine the quickest one f ...

Guide on how to restrict specific days and dates in MUI React datepicker using a JSON array

I am working on a Laravel application that generates a JSON response containing dates and days of the week that need to be disabled in the datepicker. For instance, here is an example of my datesOff constant when I log it: ['2022-05-08', '2 ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...