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