How to add a timer on page load that stops when button is clicked?

Solution 1:

Related to the jsfiddle in your comment:

Don't use this to access the button. Instead, just use document.querySelector:

document.querySelector('button').onclick = function() {
  var sec = secondsSinceEnter();
  if (sec < 10)
    document.querySelector('button').innerText = sec + " seconds";
  else
    document.querySelector('button').innerText = 'You are here like for eternity';
}

Then, you're just adding the time when the button is clicked. Additionally, you should call it every 0ms (every 'tick') using setInterval. So that you don't have to write the function twice, you could define it as a seperate function. Finally, remove the interval when the button is clicked.

Full script:

// Interval
var interval;

// Counter
var enterDate = new Date();
function secondsSinceEnter()
{
  return (new Date() - enterDate) / 1000;
}

// Event function
function evtFct()
{
  var sec = secondsSinceEnter().toFixed(3);
  if (sec < 10)
    document.querySelector('button').innerText = sec + " seconds";
  else
    document.querySelector('button').innerText = 'You are here like for eternity';
}

// Add interval to keep the current time uptodate
interval = setInterval(evtFct, 0); // Call evtFct every tick

// Usage example
document.querySelector('button').onclick = function()
{
  evtFct();
  clearInterval(interval); // Disable interval
}