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

Time:01-20

I want to add a timer to the page where it starts on page load.

Where it goes up in milliseconds.

Then stops when the mouse is clicked on the button.

How would I create a code example of that?

That is all I am trying to do in the code.

Add a timer that starts on page load.

Goes up in milliseconds.

Then stops when the button is clicked.

I want to be able to see the numbers going up.

https://jsfiddle.net/xvkwmndq/

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

    // Usage example
    document.querySelector('button').onclick = function() {
      var sec = secondsSinceEnter();
      if (sec < 10)
          this.innerText = sec   " seconds";
      else
          this.innerText = 'You are here like for eternity';
    };
.play {
      -webkit-appearance: none;
      appearance: none;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      margin: auto;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90px;
      height: 90px;
      border-radius: 50%;
      cursor: pointer;
      border: 9px solid blue;
      background: transparent;
      filter: drop-shadow(3px 3px 3px #000000b3);
    }
<button  type="button" aria-label="Open"></button>

CodePudding user response:

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
}
  •  Tags:  
  • Related