Permanent counter regardless of page refresh.

I have this jQuery piece that currently increments the number every every 5 seconds. The problem is that its client side, so it is reset every time you refresh the page.

Instead, I would like the counter to continue even if you are far from the site, and no matter how many times you refresh the page, so I thought that the server side of the script, such as PHP, would be better suited for my use case. If not, suggest another.

I installed a working script of what I have in jQuery: http://jsfiddle.net/f354bzy5/

What will PHP be like to recreate this effect, which includes my requirements above?

Here is the jQuery I use:

//Counter
var counter = 22000000000;
$(".count").html(counter);
  setInterval(function () {
  $(".count").html(counter);
  ++counter;
}, 5000);
+4
5

DEMO

//Counter
var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object')
{
   counter=parseInt(localStorage.getItem('counts'));
}
setInterval(function () {
    $(".count").html(counter);
    ++counter;
    localStorage.setItem('counts',counter);
}, 1000);

localStorage

localStorage - . no expiration date, JavaScript Browser Cache/ Locally Stored Data - .

0

cookie.

document.cookie = counter.

cookie, .

0

. , :

"" . , . , cookie .

" " . , .

0
source

You can do this with localStorage. This is how I do it. You can customize it as you need.

//detecting support for localStorage.
if (window.localStorage) {

    //counterValue already exists in localStorage? Let 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);

}
0
source

How to use localStoragewith some functions of the utility? Keep in mind that this solution is on the client side, and itemwill be deleted when the user deletes the cache browser / 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 -

0
source

All Articles