Home > Back-end >  Live counter HTML
Live counter HTML

Time:10-21

I need to create a counter that adds 1 every second like This for a work webstie please help ASAP

CodePudding user response:

Simple task for setInterval function that has an interval of 1000ms (1s). Then rais the counter every interval and display it:

window.addEventListener('DOMContentLoaded', function() {
  let counter = 0;
  setInterval(function () {
    document.querySelector('output').textContent = counter;
    counter  ;
  }, 1000);
})
/* for visualization only */
body {
  margin: 0;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

output {
  font-size: 3rem;
}
<output></output>

CodePudding user response:

  1. Stored a counter in the backend (e.g. file or db), together with the time (e.g. Unix time, 1 at 07:00:00) when it was created.

  2. Initially show the counter that is read from the backend.

  3. When user accesses website at 08:00:15, just add 3615 seconds to the display.

  4. To give a sense of "live", display with animation incrementally on the client side. E.g. current display shows 100. 5 secs later, via ajax request you get a new value 105

  • Related