Avoid starting the stopwatch and timer at the same time

How can I control the timing of a user with a button?

Currently, I can start multiple timers for different users at the same time. Is there a way to only start one timer at a time? I want the ability to pause the previous timer when starting a new one.

Is there a method to achieve this functionality?

html

<button id="button-basic" dropdownToggle aria-controls="dropdown-basic">
        <img *ngIf="taskService.timerForUsers[data.key.ID]?.currentState === 'pause' || taskService.timerForUsers[data.key.ID] == undefined" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQcW6cJlI-KlS721hkuHDTMydZ_snrkhL9sm9wYHWRhd3FlvF1b&s" width="50" height="50">
        <img *ngIf="taskService.timerForUsers[data.key.ID]?.currentState ==='start'"
        src="https://png.pngtree.com/png-clipart/20190516/original/pngtree-pause-vector-icon-png-image_3791321.jpg" width="50" height="50">
        <img *ngIf="!taskService.timerForUsers[data.key.ID]?.currentState ==='start'"
        src="https://png.pngtree.com/png-clipart/20190516/original/pngtree-pause-vector-icon-png-image_3791321.jpg" width="50" height="50">
      </button>
            <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button-basic">
                <li role="menuitem"><a class="dropdown-item"
                        *ngIf="!taskService.timerForUsers[data.key.ID] || taskService.timerForUsers[data.key.ID].currentState === 'pause'"
                        routerLinkActive="active" (click)="startTimer(data)">Start</a></li>
                <li role="menuitem"><a class="dropdown-item"
                        *ngIf="taskService.timerForUsers[data.key.ID]?.currentState === 'start'"
                        routerLinkActive="active" (click)="pauseTimer(data)">Stop</a></li>
            </ul>

Answer №1

Make the necessary adjustments to your start timer function by adding the following code:

This code snippet will first check if there are any existing timers running before starting a new timer. If there are, it will stop them and then proceed to start the requested timer.

Check out the demo here!

 startTimer(data) {

    // retrieve remaining IDs
    const pauseIds = [];
    this.data.forEach(d => {
      if (d.ID !== data.key.ID
        && this.taskService.timerForUsers[d.ID] !== undefined
        && this.taskService.timerForUsers[d.ID].currentState === 'start')
          pauseIds.push(d.ID);
    });

    // pause other timers
    pauseIds.forEach(id => {
      this.taskService.pauseTimer(id);
    });

    this.taskService.startTimer(data.key.ID);
  }

Answer №2

In order to ensure that each specific user only has one timer running at a time, you can utilize the following code:

  initiateTimer(data) {
    if(this.currentTimer){
      this.userService.stopTimer(this.currentTimer.key.ID);
    }
   this.currentTimer = data;
   this.userService.startTimer(data.key.ID);
  }

  stopTimer(data) {
    this.currentTimer = undefined;
    this.currentTimer = this.userService.stopTimer(data.key.ID);
  }

See a demonstration of this functionality in action here: https://stackblitz.com/edit/angular-sdlgqn

As Liam mentioned in a comment, if you wish to restrict users to only having one timer across requests, this logic must be implemented on the server side.

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

Tips for utilizing method overload in TypeScript with a basic object?

Looking at this code snippet: type Foo = { func(a: string): void; func(b: number, a: string): void; } const f: Foo = { func(b, a) { // ??? } } An error is encountered stating: Type '(b: number, a: string) => void' is not assign ...

Creating a generic type in TypeScript that represents a union of keys from type T's properties

Is there a way to determine the result type (TTarget) based on TSource and the provided property names (keyof TSource)? I have this function that copies specified properties to a new object: export declare type PropertyNamesOnly<T> = { [K in keyof ...

Encountering issues with Semver while working on building an Angular 4 IMAP client

I am currently working on integrating an Imap Client into my Angular 4 app. I came across a helpful node module for implementing Imap using npm: Repository However, I encountered an issue. After adding the following line in angular-cli.json: "scripts": ...

Delete an essential attribute from an entity

I am trying to remove a required property called hash from an object, but I keep encountering TypeScript or ESLint errors. All the properties of the interface are mandatory, and I do not want to make all properties optional using Partial. Here is the inte ...

Angular HTTP Interceptor encountering issue with TypeError: (0 , x.fromPromise) function is not recognized

I have implemented the following code snippet to attach reCAPTCHA v3 to an HTTP Request: @Injectable() export class RecaptchaInterceptor implements HttpInterceptor { constructor(private recaptchaService: ReCaptchaService) { } intercept(httpRequest: HttpRe ...

What is the best way to extend a class in NestJS from another class?

I've encountered an issue while attempting to extend a class service from another class service in NestJS and utilize DI to load it in a third service. The error message I'm receiving from Nest is: Error: Nest can't resolve dependencies of ...

Error in Angular 5: Cannot find property 'then' in type 'Observable<any>'

I encountered the following error message: "[ts] Property 'then' does not exist on type 'Observable'. How can I resolve this issue? Below is my Component code: getUsers(){ this.authService.getUsers().then((res) => { thi ...

Troubleshooting Issue: Relative Paths Fail to Work with routerLink in Angular 6

I seem to be encountering a problem with the Angular app I'm currently developing. It appears that when using relative paths with routerLink throughout the application, it fails to work properly. There are no errors thrown and the navigation does not ...

Creating a unique Tag Name for Dynamic Components in Angular

I want to customize a component @Component({ selector: '[my-component]', template: `<i>1</i><p>content</p><b>2</b>` }) export class MyComponent { public tagName: string; } Then there's another comp ...

Is it possible for a React selector to retrieve a particular data type?

As a newcomer to React and Typescript, I am currently exploring whether a selector can be configured to return a custom type. Below is a basic selector that returns a user of type Map<string, any>: selectors/user.ts import { createSelector } from ...

Simulation service agent partnered with openApi backend

I am currently utilizing MSW along with the OpenAPI-backend package for my project. I aim to mock both the browser server and test server using OpenAPI specifications. With an available OpenAPI definition, I generate `generated.ts` for RTK Query (which is ...

Exploring Typescript Reflection: The Importance of Required Parameters and Default Values

In summary: Is there a method to determine whether a typescript parameter is mandatory and/or has a preset value? Expanding further: Imagine I have the code snippet below: //Foo.ts class Bar { foo(required:string,defaultValue:number=0,optional?:boole ...

Angular Fusion: Delay execution of ngAfterViewInit until data is received from API call in ngOnInit

I'm facing an issue with my code where the API call in ngOnInit is not waiting for the data to be returned before moving on to ngAfterViewInit. I need it to wait because I am performing operations on that data in ngAfterViewInit, but currently, it&apo ...

Determining the presence of an object within an array of objects in Angular

I am currently working with Angular 8 and I need to check if an object exists within an array of objects. Here is the object I want to check for: let objVenIns = { 'CntNumber': 4, 'CntMixer': 2, ...

What could be causing Highlight.js to fail to work following a redirect?

After developing a small application to address a specific issue, I encountered a problem while attempting to apply code highlighting using highlight.js. The issue arises when navigating from site1 to site2 or vice versa - the highlight does not take effec ...

In TypeScript, vertical bars and null are commonly used for type unions

Greetings! I am just starting to learn JavaScript and TypeScript I have a question about the code snippet below What does the pipe symbol (|) signify? Also, why is null = null being used here? let element: HTMLElement | null = null; ...

Adding a personalized service into a separate service within Angular 2

I am having trouble injecting my own service into another service. While I can inject standard Angular services like Http without any issues, attempting to inject custom services results in an exception. For example, here is how MyService is set up: impo ...

What is the best way to insert CSS code into a custom Vue directive file?

I need a solution that applies a gradient background to the parent div in case an image fails to load. I've attempted to create a directive for this purpose: export default { bind(el: any, binding: any) { try { ..... ...

Assign a distinct color to a row depending on the row's characteristic

One of my tasks involves implementing row highlights with specific colors based on their attributes. For instance, when displaying employee records, I need to show all employees whose highest education column is not null in green. The current code snippet ...

Guide to implementing an enum in an Angular Component

Having a global state (or "mode") in my Angular Components is leading me to look for more efficient ways to code. Here is what I have tried: @Component({ .... }) export class AbcComponent implements OnInit { enum State { init, view, edit, cre ...