简体   繁体   中英

Increase the value of a number in an element every x time - Not Disappeared

Okay i need Javascript what will work, that every X time number will increase, but when i refresh browser this number not disappear and stay in online (saving)

var i = 0; // Value starts off at zero

function increment() {

i++; // Change to i += [yourvalue] for any increase other than 1

document.getElementById('count').innerHTML = i;

}

setInterval('increment()', 2000); // Increments every 2 seconds

I have this it`s working but when i refresh increase time disappearing

In a function you are incrementing X value, set it to local storage.

localStorage.setItem('X', value);

Similarly, get the item from localStorage and set it as the initial value.

var x = localStorage.getItem('X') || 0
                    function increment() {
                    var n = localStorage.getItem('on_load_counter');
                    if (n === null) {
                        n = 0;
                    }
                    
                    n++;
               
                    
                    localStorage.setItem("on_load_counter", n);
                    
                    document.getElementById('counter').innerHTML = n;
                     }
                    setInterval('increment()', 2000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM