Continual counter regardless of page refresh

后端 未结 5 1759
不知归路
不知归路 2021-01-13 17:14

I have this piece of jQuery that currently increments a number by one every 5 seconds. The problem I have is that its client side, therefore it resets every time you refresh

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 17:43

    You could do it with localStorage. Here's how I am doing it. You can tweak it as you need.

    //detecting support for localStorage.
    if (window.localStorage) {
    
        //counterValue already exists in localStorage? Let's use that or set to zero.
        var counterValue = localStorage.counterValue || 0;
    
        setInterval(function() {
            //increment the counter and store updated vale in localStorage as well.
            localStorage.counterValue = ++counterValue;
    
            //put it in your HTML if you might
            $(".count").html(counterValue);
        }, 5000);
    
    }
    

提交回复
热议问题