0

Is there a way to keep a variable value on page refresh, if I have

var x=0;

but then a users does something that makes that value become

x=4;

and then the page is refreshed, is there a way to keep that value of 4 for the x variable or it will always reset to the original value?

I have written 2 functions to set and get the value like this:

     function SetlifeCounter()
      {
        life = 3;
        localStorage.setItem("life", life);
       }

      function GetlifeCounter()
       {
         life1 = localStorage.getItem("life");
           life1=life1-1;
         return life1;
       }

And then calling them this way:

  var mainLife;
  SetlifeCounter();
    mainLife=GetlifeCounter();
    while(mainLife!=0)
    {

        window.location.reload();
    }

But when I run this the page freezes... What m I doing wrong??

P.S this is to keep track of the no. of lives in a game every time you die(page reloads) in the game life gets deducted.

2
  • 2
    Yes, use localStorage. Commented Feb 1, 2017 at 14:56
  • It'll always reset - you'd have to use persistent storage like e.g. localStorage Commented Feb 1, 2017 at 14:56

2 Answers 2

2

Yes, use localStorage.

When using persisted values, you'll need to check to see if a value was already saved (from the user's previous visit) and, if so, use that. If not, you'll need to create a value and set it into storage so that it can be used on a subsequent visit.

This is generally done like this:

var x = null;

// Check to see if there is already a value in localStorage
if(localStorage.getItem("x")){

  // Value exists. Get it assign it:
  x = localStorage.getItem("x");

} else {

  // Value doesn't exist. Set it locally and store it for future visits
  x = 3.14;
  x = Math.floor(x);

  localStorage.setItem("x", x); 

}

In your example, you have a variety of issues, but the browser locking up was due to the while loop, which was creating an infinite loop whenever the life count was not zero. You must be VERY careful with while loops and ensure that they will always have a termination condition that will be hit. But, for your purposes, this was unnecessary anyway.

See comments inline below for details on the correct usage of localStorage.

NOTE: This code won't work here in the Stack Overflow code snippet editor due to sandboxing, but you can see this working example here.

// This is where you will store the lives remaining
// You don't need several variables to keep track of this
// (mainLife, life, life1). Just modify this one variable as needed.
var lifeCount = null;

// As soon as the user arrives at the page, get or set the life count 
window.addEventListener("DOMContentLoaded", initLifeCount);

// By convention use camelCase for identifier names that aren't constructors
// and put opening curly brace on same line as declaration
function initLifeCount() {

  // You need to test to see if an item exists in localStorage before getting it
  if(localStorage.getItem("life")){
  
    // And, remember that localStorage values are stored as strings, so you must
    // convert them to numbers before doing math with them.
    lifeCount = parseInt(localStorage.getItem("life"), 10) - 1;
    
    // Test to see if there are any lives left
    if(lifeCount === 0){
    	// Invoke "Game Over" code
      alert("Game Over!");
    }
        
  } else {
    // User hasn't previously stored a count, so they must be starting a new game
    lifeCount = 3;
  }
  
  // Any time the count changes, remember to update it in localStorage
  updateLifeCount();

  // Temporary code for debugging:
  console.log("Life count is: " + lifeCount);
}

// Call this function after the life count changes during game play
function updateLifeCount(){
  localStorage.setItem("life", lifeCount)
}

If you open your developer tools (F12) and navigate to view the localStorage, you will be able to see the value decrease every time you re-run the Fiddle. You can also see the value in the console.

enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Please have a look at the updated post tell me where I'am going wrong
@caitancorreia You have several issues.... I'm working on an edit to my answer. Wait a few minutes for the update.
@caitancorreia Ok, take a look at my updated answer.
0

Many. You can choose between cookies, local storage, web sql, remote backend...

See this question about setting the value inside a cookie:

Set cookie and get cookie with JavaScript

For local storage, use:

localStorage.setItem("x", x);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.