1

Here I declared a variable with value from local storage var yourLink = parseInt(localStorage.getItem('linkID')); but the problem is when there is no value for the first time this is not working. So, I tried to add another if statement where there is no value found then assign a value to the yourLink variable. But couldn't do it. What can I try next?

Here I give the full code:

var link = ["https://www.facebook.com/", "https://stackoverflow.com/"];


var yourLink = parseInt(localStorage.getItem('linkID'));



localStorage.setItem('linkID', yourLink);


if ((parseInt(localStorage.getItem('linkID')))<= 7 ) {
    yourLink = parseInt(localStorage.getItem('linkID')) + 1;
    localStorage.setItem('linkID', yourLink);

    yourLink = parseInt(localStorage.getItem('linkID'))

    window.open(link[0], '_blank');


} else if ((parseInt(localStorage.getItem('linkID'))) >= 8) {
    yourLink = parseInt(localStorage.getItem('linkID')) + 1;
    localStorage.setItem('linkID', yourLink);

    yourLink = parseInt(localStorage.getItem('linkID'))

    window.open(link[1], '_blank');

    yourLink = 0;
    localStorage.setItem('linkID', yourLink);
}
halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

0

You can use this condition for determining whether it is the first time

if(localStorage.getItem('linkID') == null){
    // do your logic here
}
tcf01
  • 1,699
  • 1
  • 9
  • 24
0

Here in your question, none of the times the data is being set in localStorage as parseInt(localStorage.getItem('linkID')) will be NaN. So what you can do is


var link = ["https://www.facebook.com/", "https://stackoverflow.com/"];

if(!localStorage.getItem('linkID')) {
   localStorage.setItem('linkID', 0);
}

if ((parseInt(localStorage.getItem('linkID')))<= 7 ) {
    yourLink = parseInt(localStorage.getItem('linkID')) + 1;
    localStorage.setItem('linkID', yourLink);

    yourLink = parseInt(localStorage.getItem('linkID'))

    window.open(link[0], '_blank');

} else if ((parseInt(localStorage.getItem('linkID'))) >= 8) {
    yourLink = parseInt(localStorage.getItem('linkID')) + 1;
    localStorage.setItem('linkID', yourLink);

    yourLink = parseInt(localStorage.getItem('linkID'))

    window.open(link[1], '_blank');

    yourLink = 0;
    localStorage.setItem('linkID', yourLink);
}

Hope this helps in solving your problem.

Nithish
  • 5,393
  • 2
  • 9
  • 24