Is there a way to see the countdown timers in Angular 7?

Is there a way for me to view my timer's countdown as it starts? I have attempted to bind it to a variable, but all I see is [object Object]:

setTime(time) {
    if (this.settime >= 5 ) {
      this.currentTime = time;
      this.alerttime = this.settime;
    this.notifiy.showInfo( 'Timer set for ' + this.settime + ' Minutes train is due in ' + time + ' Minutes' , '');
    const val = this.settime * 60000;
    const source = timer(val);
    this.time = source;
    console.log(this.time); // this prints out the observbale function Ive also tryed to bind it in the subscribe method but no joy.
    const subscribe = source.subscribe(value => { this.alertTimer(); });
    this.settime = '';
    //cordova.plugins.backgroundMode.enable();
    } else {
      this.notifiy.showFailure('You cant set the timer below 5 minutes', '');
    }
  }

I'm struggling to pinpoint where I may be going astray.

Answer №1

The simple answer is that it's not possible because the timer you are currently using doesn't support this feature, as mentioned in the documentation.

However, if you need to keep track of the elapsed time separately, you can consider using the "interval" function instead.

Here is an example of how you can achieve this using a combination of `timer()` and `interval()`:

Say you set a timer for 120 seconds using `timer()`, and then use `interval()` to track the elapsed time and update the UI until the main timer ends.

Here is a basic implementation to demonstrate the concept:

class TimerManager {

   private totalSeconds;
   private elapsedSeconds;
   private timerSub;
   private intervalSub;

   // Start the timer
   public startTimer(timerLengthSeconds) {
      this.totalSeconds = timerLengthSeconds;
      var t = new timer(timerLengthSeconds);
      this.timerSub = t.subscribe(t => this.endTimer());
      var i = new interval(1000);
      this.intervalSub = i.subscribe(i => this.intervalElapsed());
   }

   // Track each interval
   private intervalElapsed() {
      this.elapsedSeconds++;
      var remaining = this.totalSeconds - this.elapsedSeconds;
      console.log(this.elapsedSeconds + "s have passed, " + remaining + "s remaining");
   }

   // End the main timer
   private endTimer() {
     console.log("Time's up!");
     this.intervalSub.unsubscribe();
   }
}

Answer №2

If you want to see a timer countdown, you can utilize the set interval function. Below is an example that demonstrates how you can implement this feature, which can also be used in Type Script. I believe this solution will be helpful in addressing your issue.

// Setting a 120-second timer...
var timeleft = 120;
var downloadTimer = setInterval(function() {
  if (timeleft <= 0) {
    clearInterval(downloadTimer);
    document.getElementById("countdown").innerHTML = "Finished";
  } else {
    document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";
  }
  timeleft -= 1;
}, 1000);
<div id="countdown"></div>

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

Custom virtual properties can be set in Mongoose by utilizing the return value in a callback function

I've been searching all over for a solution to my issue, but I can't seem to find the right answer. I'm currently using MongooseJS as my ODM and I'm attempting to create virtual getters that can retrieve, process, and display informatio ...

Interactive 3D model movable within designated area | R3F

I am currently facing a challenge in limiting the drag area of my 3D models to the floor within my FinalRoom.glb model. After converting it to tsx using gltfjsx, I obtained the following code: import * as THREE from "three"; import React, { useRe ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Tips to center a circular progress bar in Material UI

Does anyone know how to properly center-align a circular progress bar in a login form using material UI? I'm having trouble with it not being positioned correctly: screenshot {isLoading && <CircularProgress />} {user?.ema ...

remain on the multi drop down page for a specified duration

I have created a dropdown menu with a second level drop-down page that is a form. Now, I want the second level drop-down page to stay open longer, so I have used the following JavaScript code: <script> var timer; $(".parent").on("mouseover", functio ...

Injecting an attribute with the forbidden character "@" into the Document Object Model (DOM

Scenario I find myself needing to update some existing HTML using JavaScript, but I'm limited in that the server side is out of my control. This means that any changes must be made client-side only without altering the original HTML document. To acc ...

The magic of data binding in AngularJS's ng-repeat

Is it possible to dynamically call an attribute of a data-binded object based on the ng-repeat object? I have set up a simple example, but I'm not sure if it can be solved this way. Can anyone help with this? The goal is for the input to receive the ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

The Material-UI selector isn't functioning properly for me

I recently tried to incorporate a material-ui selector example into my project by referring to the code fragment obtained from an example on Github. import React from "react"; import {withStyles} from "material-ui/styles"; import Select from "material-ui/ ...

What is the best way to retrieve the name of a static method within a class?

In my code, I am logging multiple messages in a static method and I want to use the method name as context. However, I do not want to create a separate variable called `context` and assign the function/method name to it. I would like to be able to access ...

How can I configure Angular to redirect to an error page whenever an error is encountered in an HTTP API request?

With over 50 HTTP APIs in my application, I'm looking for a way to automatically route to a specific page whenever an error message or issue arises with one of the APIs. Instead of manually adding routing to each service, I want to find a simpler and ...

What is the method for making an interface extension from a type as optional?

Can you help me create an interface that includes all students and part of a school, ensuring that gender is required for Peter and optional for other students? export type School = { address: string; state: string; }; export type Gender = { gender: ...

Having trouble implementing the Material UI time picker because it does not meet the required DateTime format

REVISE I recently switched my dataType from DateTime to TimeSpan in my code. I have a functioning MVC version that already uses TimeSpan, and the times are posted in HH:MM format. Now, I am unsure if the issue lies with the headers set up on Axios or if it ...

Node.js seems to be having trouble with emitting events and catching them

I'm having trouble troubleshooting my code. // emitter.js var EventEmitter = require('events').EventEmitter; var util = require('util'); function Loadfun(param1, param2, db){ function __error(error, row){ if(error){ ...

Tips for transferring information to a textarea within a bootstrap modal by selecting a cell in a table

I need to enable users to edit information in a table. One cell in the table contains text. Here is an excerpt from the table: <table class="table table-striped table-hover" id="table_id"> <thead> <tr> <th>Event</th& ...

After calling the use method in Express, utilizing the get method

const express = require("express"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use((req, res, next) => { console.log("Executing first middlewar ...

Switch the style of a set of thumbnail images when clicked

I am working with a set of thumbnails where one has an "p7_current" class applied, giving it a border, while the rest have an "p7_inactive" class removing the border. My goal is to have the last clicked thumbnail in a group of 6 to have the "p7_current" c ...

Transferring a Sharepoint 2010 List Item between folders

Currently, I am facing an issue while attempting to transfer a list item from one folder to another. Despite utilizing a code that I discovered (the link to the source of the code can be found below), I keep encountering an error message stating "Value doe ...

What is the best way to determine the width of a scroll bar?

Are you familiar with any techniques that work across multiple browsers? ...

Error encountered while attempting to convert CSV file: InvalidStateError

I've implemented a JavaScript function to be triggered by the 'onclick' event of an HTML button: function exportReportData2() { if ($("#Report").val() != "") { var screenParametersList = buildScreenParameters(); var ...