Show the alert notification just one time every hour in the event that it occurs

I've been struggling to figure out where I'm going wrong with this implementation. Essentially, errors can occur for various reasons, but I only want to display the alert message once every fifteen minutes. For example, if an error occurs at 7:02AM, it should trigger the alert. However, if another error occurs at 7:10AM, it should not display. But if an error happens after 8:02AM, then the alert should show again and the cycle continues.

Currently, the alert message is being displayed regardless of what I try to fix it.

lastTimeErrorWasDisplayed = 0;
displayError() {

    let vm : any = this;

    // get the current time
    const timeNow = new Date().getTime();

    const hoursToWaitBeforeNextToastr = 1;

    const difference = timeNow  - this.lastTimeErrorWasDisplayed
    var hours = (difference / (1000 * 60 * 60));
    // should we show toastr now?
    if (
      hours > hoursToWaitBeforeNextToastr
    ) {
      this.lastTimeErrorWasDisplayed = timeNow;

      setTimeout(() => {
        vm.toastr.warning(
         "error",""
        );
      });


    }
}

The setTimeout is necessary due to the application requirements. Even without it, however, the error still shows up regardless of when it occurred or was last displayed.

Answer №1

Give this a shot:

let startTime = new Date('2019/06/30 16:00');
let currentTime = new Date();
let timeDifference = currentTime.getTime() - startTime.getTime();
let resultInMinutes = Math.round(timeDifference / 60000);

if (resultInMinutes >= 15) {
 // your code
}

If you prefer, you can also update the if-condition to 60 to check every hour instead.

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

Leverage the source code of Angular 2 in your project for seamless integration

Currently in the process of setting up Angular with npm: npm install @angular... Encountering an issue where the TypeScript source files are not included. I would like to have access to debug the code using the TypeScript source files (with source maps). ...

Unleashing the power of joint queries in Sequelize

Project.data.ts import { DataTypes, Model, CreationOptional, InferCreationAttributes, InferAttributes, BelongsToManyGetAssociationsMixin, BelongsToManySetAssociationsMixin, BelongsToManyAddAssociationsMixin } from 'sequelize'; import sequelize fr ...

Using React.Fragment in VS Code with TypeScript error 2605 while having checkJs enabled

While utilizing the JS type checking feature in VScode, I encountered an issue with React.Fragment that is being linted with an error: JSX element type 'ReactElement<any>' is not a constructor function for JSX elements. Type 'ReactEle ...

Expand the ApiGateProxyEvent category from aws-lambda

Looking to enhance the ApiGateProxyEvent of aws-lambda in d.ts. Initial attempts replaced the entire APIGatewayProxyEvent instead of extending it as intended. declare namespace AWSLambda { interface APIGatewayProxyEvent { body: any; user: any; ...

The Typescript module in question does not contain any exported components or functions related to

I've encountered an unusual issue while working on a React, Redux TypeScript application. It seems that after making some changes, one of the modules has stopped exporting its members. Here is the folder structure: src |---- components |---- contain ...

Steps for displaying API Response in a material-table

In my project, I have a component named List which displays data using mat-cards. When a specific mat-card is clicked, it navigates to another component called home. In this home component, the data from the selected mat-card is displayed within another ma ...

What is causing the undefined value for the http used in this function?

My Code Component import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app-root', template: '<button id="testBtn"></button>' }) export c ...

Prevent redundancy by caching svg icons to minimize repeated requests

I have a collection of info cards on my page, each featuring its own unique illustration along with a set of common icons (SVG) for options such as edit, delete, and more. While the illustrations vary from card to card, the icons remain consistent across a ...

Extracting values from dynamically named properties in ES6 using object destructuring

let currentFilter: Product = { name: 'iphone', price: 30, createdDate: '11-11-2020' } My code is structured around a specific filter. The filter data is structured in the following format: I have a table with different filters. ...

Display the notification list by utilizing the "ToastController" function

Upon entering the home screen, I want to notify the user by displaying a list of messages from a firebase collection. The field to be displayed is "text", but I only want to show messages with the "read" field set as false. Once a message is shown, its "re ...

Can classes from an external package be imported into an Angular library within an Angular app using Openlayers?

I am currently developing an Angular library that configures an OpenLayers map as an Angular component. The component is functioning properly, but I need to access classes and constants from a package imported by the library, specifically OpenLayers. To w ...

Error encountered: "The requested resource does not have the 'Access-Control-Allow-Origin' header in Angular 6 and Nodejs."

I have encountered an issue with my Angular 6 app and Node.js. When I submit the form, I am receiving the following error: Failed to load http://localhost:3000/contact/send: Response to preflight request doesn't pass access control check: No 'Ac ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Navigating with Angular 2 @angular/router 3.0.0-alpha.7 - Handling Multiple Parameters

Currently experimenting with the new Angular 2 router, specifically Angular 2 @angular/router 3.0.0-alpha.7 As per my understanding, route parameters can be accessed in the new router using the following code: this.activatedRoute.params .map( ...

Import a Component Dynamically Using a Variable in AngularJS

I am attempting to dynamically load a component using a variable, but I keep running into an "Uncaught Error: Template parse errors". How can I achieve this successfully? <app-{{ this.plugin.component }}></app-{{ this.plugin.component }}> ...

Ways to display an icon upon hovering or clicking, then conceal it when the mouse is moved away or another list item is clicked using ngFor in Angular 7

Within a simple loop, I have created a list with multiple rows. When a row is clicked or hovered over, it becomes active. Subsequently, clicking on another row will deactivate the previous one and activate the new one. So far, everything is functioning c ...

cycle through options of radio buttons

How can I display items of radio buttons, with the values of these items coming from a backend api? <div class="input-group col-md-9 input-group-sm"> <label>gender</label> </div> <!-- TO CORRECT ...

Is it possible for me to reinstall npm in an Angular project as a solution?

I recently started working on an Angular 9 project and installed various libraries. However, I encountered some issues with ngx-gallery and Renderer2 which led me to make edits in files like core.d.ts within the node_module/angular/core directory. As a new ...

Guide to fetching a string using Angular's http client?

I am facing an issue with calling a server that returns a csv file as text. I am using Angular's HttpClient and I need to prevent it from trying to cast the csv file to JSON. I tried setting the responseType to 'text' in the httpOptions, but ...

Error: A stream was expected, but you provided 'undefined'. Please provide either an Observable, Promise, Array, or Iterable instead

I'm encountering an error while trying to catch errors in my Ionic-based application with Angular. In the create() method, I am attempting to create a new User. If the username already exists, I receive a response from the backend, but my method thro ...