user13780186
user13780186

Reputation:

How to setTimeout will not repeat when reload in Angular

I have some data and its processing code as follows:

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);
}

What I'm trying to do here is when opening the application it will list all the data LIST from the console once even it will change a page or reload the page it shouldn't repeat and when clicking on the addData() it will add the new data then by initializeAlertTime() it will display the newest data.

Upvotes: 0

Views: 253

Answers (2)

Minal Shah
Minal Shah

Reputation: 1486

When you reload the application, all your variables and stack gets reinitialized. So there is no way to track whether the user has visited the firs time of just reloaded the application.

You can store some value in your database to keep track or use localstorage or session storage.

If you want to keep track while changing the screen that could be possible by using the service and defining the variable.

When you user visits the page for second time you just check the value of the variable stored in the service.

Upvotes: 1

Y Munawwer
Y Munawwer

Reputation: 126

There are many ways to do the same ex: 1)Using localstorage, 2)sessionstorage 3)service class

localstorage

Save into LocalStorage:

localStorage.setItem('key', value);

For objects with properties:

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

Get From Local Storage:

localStorage.getItem('key');

For objects:

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

And you can use this part of the code to get remaining time

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

when needed

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

Note:Value will be reserve when reload 2)localStorage Object will save data as string and retrieve as string. You need to Parse desired output if value is object stored as string. e.g. parseInt(localStorage.getItem('key'));

Upvotes: 2

Related Questions