'Persistent timer on HTML page load

I have this persistent JavaScript timer. I want to start the timer on page load of an HTML page (and maybe end it on a specific page).

HTML:

<div>Time remaining: <span id="timer"></span></div>

JavaScript:

var interval = 30000;

function reset()
{
    localStorage.endTime = +new Date + interval;
}

if(!localStorage.endTime)
{
    reset();
}

setInterval(function()
{
    var remaining = localStorage.endTime - new Date;
    if( remaining >= 0 )
    {
        $('#timer').text( Math.floor( remaining / 1000 ) );
    } else
    {
        reset();
    }
}, 100);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source