-4

I have a speed element in my game however, whenever you fail it refreshes the page. I do not want people to have to keep resetting their speed every time the page refreshes. How can I keep the variable the same even after a page refresh?

Thankyou

Moz
  • 31
  • 3
  • 1
    You would need to save the variable to `LocalStorage` as an easy solution, or have them create an account and save the data server side so they can't alter it. It depends on how critical that data is. – Carcigenicate Dec 23 '18 at 15:45

1 Answers1

0

Here you go, this will do the trick. Just dont set the speed directly though the variable but use the setSpeed function which will update the localstorage aswell.

let speed = localStorage.getItem('speed') ? Number(localStorage.getItem('speed')) : 0; // or whatever your default speed is

function setSpeed(newSpeed) {
    speed = newSpeed;
    localStorage.setItem('speed', newSpeed);
}

Another solution would be to use get and set methods, this one is more elegant, once you set speed it will automatically be stored in the localstrage.

(function() {
    let _speed = localStorage.getItem('speed') ? Number(localStorage.getItem('speed')) : 0;

    Object.defineProperty(this, 'speed', {
        get: function() {
            return _speed;
        },
        set: function(speed) {
            _speed = speed;
            localStorage.setItem('speed', speed)
            return true;
        }
    });
})();
nikksan
  • 3,341
  • 3
  • 22
  • 27