Preventing setTimeout from repeating upon reload in Angular

I have a dataset and processing code shown below:

LIST = [{
    "id": "1lqgDs6cZdWBL",
    "timeUpdated": "2020-04-22 12:51:23",
    "status": "CLOSED"
}, {
    "id": "C2Zl9JWfZHSJ",
    "timeUpdated": "2020-04-22 12:51:07",
    "status": "CLOSED"
}, {
    "id": "BHbiVcCaQa2d",
    "timeUpdated": "2020-04-15 14:53:12",
    "status": "CLOSED"
}];


ngOnInit() {
  this.initializeAlertTimer();
}
initializeAlertTimer(data?: any, duration?: any) {
  const DURATION = duration ? 20000 : 1000
  setTimeout(() => {
  }, DURATION)
}

addData() {
  const data = {
     "id": "qHFw59mujN9X",
     "timeCreated": "2020-03-06 12:21:06",
     "status": "NEW",
   }
   this.initializeAlertTimer(data, 20000);
}

My goal is to display the LIST data in the console only once when the application is opened. Even if there are page changes or reloads, it should not repeat. When clicking on addData(), new data will be added and the newest data will be displayed through initializeAlertTime().

Answer №1

There are several methods to achieve the same result: 1)Utilizing local storage, 2)session storage 3)service classes

Local Storage

Saving data into LocalStorage:

localStorage.setItem('key', value);

For objects with properties:

localStorage.setItem('key', JSON.stringify(object));

Retrieving From Local Storage:

localStorage.getItem('key');

For objects:

JSON.parse(localStorage.getItem('key'));

You can also utilize this code snippet to calculate remaining time

localStorage.setItem('DURATION', DURATION)
    localStorage.setItem('start', Date.now()) // in milliseconds
    

when necessary

    const elapsed = Date.now() - localStorage.getItem('start');
    const remaining =  localStorage.setItem('DURATION') - elapsed; // divide by 1000 for seconds

Note:The value will persist even after reloading the page. 2)localStorage Object stores data as a string and retrieves it as a string. You may need to Parse the desired output if the value is an object stored as a string, e.g. parseInt(localStorage.getItem('key'));

Answer №2

When the application is reloaded, all variables and stack are reset. This means it's not possible to determine whether the user is visiting for the first time or just reloading the app.

To track this information, you can store a value in your database, use localstorage, or utilize session storage.

If you need to keep track while switching screens, you can achieve this by creating a service and defining the variable within it.

Upon the user's second visit to the page, you can simply check the stored value of the variable in the service.

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

What is the best way to invoke parent component methods from a child component?

I'm struggling with a scenario where I want to call methods— _handleFirstName and _handleLastName— from the parent component <Home/>, in a child component named <NormalTextField/>. The ultimate goal is to allow the user to input text, ...

Discovering objects nested within other objects

I am currently attempting to locate a specific element within another element. The structure of my HTML looks like this: <div> <label>test</label> <div> <a>testlink</a> <input type=&apos ...

The enigma of the Angular2 Object's Undefined nature

Encountering an "object undefined" error when trying to access the object of the Service Component. Interestingly, hard coding the data directly into a JavaScript variable works fine and shows the type as "object Array." Data.json [ { "id": ...

Changing Databases in a NextJS Application using Mongoose

Recently, I've been exploring the idea of integrating database switching into a NextJS application. While I am somewhat new to NextJS as a framework, I do have previous experience working with NodeJS and React. In a Node environment, this concept migh ...

Issue with web form layout and heading malfunction

I'm experimenting with creating a form and dynamically setting the pattern and title fields using JavaScript. I am facing an issue with the current code as it is preventing me from entering anything into the form field, and displaying an error message ...

Looking for a way to manipulate the items in my cart by adding, removing, increasing quantity, and adjusting prices accordingly. Created by Telmo

I am currently working on enhancing telmo sampiao's shopping cart series code by adding functionality for removing items and implementing increment/decrement buttons, all while incorporating local storage to store the data. function displayCart(){ ...

What is the process for transforming a string literal type into the keys of a different type?

Imagine having a string literal type like this: type Letters = "a" | "b" | "c" | "d" | "e"; Is there a way to create the following type based on Letters? type LetterFlags = {a: boolean, b: boolean, c: bool ...

javascript - The onmessage event will not trigger when using a Java server

I have encountered an issue with my Java server and JavaScript websocket client. Despite trying various solutions from this site, I am still unable to resolve the problem. So, I decided to share my code here in hopes of getting some assistance. The proble ...

Converting a database query result into a JavaScript variable: A step-by-step guide

I've been struggling with this problem for a day now and I feel like giving up. My main goal is to export the query result as a string (specifically dataString) so that I can easily import it as a string in my external .js file. module.exports.getKl ...

The functionality of JQuery ceases to function properly once the BxSlider plugin is activated

I've encountered a strange issue while using the BxSlider plugin of jQuery on my page. When I implement the code for the slider with BxSlider, all other custom functions seem to stop working without any errors being displayed in the console. I've ...

When I use Ajax to update my HTML, it causes Javascript to malfunction

Encountering an issue with a web application I've been developing recently, specifically related to ajax reloading causing javascript to fail. The following Ajax Call is in place $.ajax({ type: "POST", url: "/sortByI ...

Having trouble with JavaScript's Date.getUTCMilliSeconds() function?

I have a straightforward question for you. Take a look at this Angular App and try to create a new date, then print the number of UTC milliseconds of that date in the console. Can you figure out why it is returning zero? ...

Ways to eliminate additional data points on the x-axis in Highcharts

I'm currently using Highcharts to plot data for specific ID's, but I'm experiencing a display issue where extra data points are showing up on the x-axis. I only want to show certain data points on the x-axis and am not sure how to remove the ...

IE9 causing issues with Angularjs ng-route - views fail to display

I am new to AngularJS and currently working on developing an application using AngularJS along with Coldfusion for database data retrieval. However, I am facing compatibility issues specifically with IE9 (which is the default browser in my office). The ap ...

Troubleshooting an Angular application

Just diving into Angular and following along with the tutorial on https://angular.io/tutorial. However, I seem to be facing an issue in Chrome where the const HEROES is not available in my watch list. It keeps showing as "not available". What could be ca ...

What is the method for obtaining multiple indices on an Array?

Attempting to find multiple index positions in an Array for a Boolean value. Experimenting with while and for loops to iterate through more than one index position without success so far. Below is the code snippet: let jo = [1,2,3,4,5] let ji = [1,2,3] ...

md-table - Adjusting the width of columns

As I work on my project, I have begun utilizing the md-table and now I am in need of fixed column width. At present, all columns are distributed evenly in size. Can anyone direct me to documentation on data table dimensions? https://material.angular.io/c ...

Scope ng-repeat with Angular's $compile function is not functioning as expected

I am facing an issue with my directive that uses the $compile service to create a template. Despite having the users array defined in my scope, it does not populate the select options using either ng-options or ng-repeat. I am puzzled as to why this is h ...

Can a rotation animation be incorporated into an image in next.js when it is clicked?

Looking to enhance a next.js image with an animation? How about making it rotate 360 degrees upon each click? Despite my attempts at toggling classes, I can't seem to achieve the desired outcome. Any guidance would be greatly appreciated. Thank you in ...

Verify the Javascript for file upload in ASP.NET folder prior to uploading it

Struggling with this problem for days now, I could really use some fresh perspective. My setup includes Windows Server 2012, IIS 8.0, and ASP.NET 4.5. I'm new to both IIS and ASP.NET, so please bear with me. The website I'm working on involves f ...