Continual counter regardless of page refresh

后端 未结 5 1793
不知归路
不知归路 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条回答
  •  萌比男神i
    2021-01-13 17:43

    How about using localStorage with some utility functions? Bear in mind that this is a client side solution and the item would be wiped off when the user deletes the browser cache/local data etc.

    function isLocalStorage() {
        try {
            return 'localStorage' in window && window['localStorage'] !== null;
        } catch(e) {
            return false;
        }
    }
    
    function setCounter(key, val) {
        localStorage.setItem(key, val);
    }
    
    function getCounter(key) {
        return parseInt(localStorage.getItem(key), 10);
    }
    
    (function() {
    
        var key = "myCounter";
        var counter = isLocalStorage() && getCounter(key) || 1;
        var $placeholder = $(".count");
        $placeholder.html(counter);
    
        setInterval(function () {
            counter++;
            $placeholder.html(counter);
            isLocalStorage() && setCounter(key, counter);
        }, 2000);
    }());
    

    -- Demo --

提交回复
热议问题