programnewb
programnewb

Reputation: 27

problems with setinterval function

I'm trying to create a simple javascript counter using the setinterval function

What I have is the following. it works just fine but it resets whenever I hit refresh. What do I do to make sure that the counter continues even if someone hits the refresh button?

Thanks!

<script type="text/javascript">
    count = 1000;
    window.onload = init;

    function init() {
        window.setInterval(incre,1000);
    }

    function incre(){
        count++;
        document.getElementById('out').innerHTML = count;
    }       
</script>

Upvotes: -1

Views: 172

Answers (1)

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

You could use sessionStorage to store the counter every time you increment it:

function incre() {
    var count = sessionStorage.getItem("myCounter") || 1000; // set it to 1000 as per your initialization
    count++;
    sessionStorage.setItem("myCounter", count);
    document.getElementById('out').innerHTML = count;
}

Upvotes: 2

Related Questions