15

On my website, I am trying to count (and display) how many seconds (not minutes or hours) the user has been on my site. So, if they have been on it for 5 minutes, it will display 300, Not 5 minutes. I am Very Unexperienced with JavaScript, So please help.

jcb1032
  • 627
  • 2
  • 5
  • 14
  • go to this link and check it out similar question : http://stackoverflow.com/questions/5517597/plain-count-up-timer-in-javascript – Vatsal Pathak May 12 '16 at 13:00

2 Answers2

31

You can use the setInterval function to run another function as often as you choose. For example:

var seconds = 0;
var el = document.getElementById('seconds-counter');

function incrementSeconds() {
    seconds += 1;
    el.innerText = "You have been here for " + seconds + " seconds.";
}

var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>

If you run this snippet, you'll see the counter working.

The setInterval function takes two parameters:

  • the function you want to call
  • the number of milliseconds between calls

Since you want to call increment the counter every second, you want to use 1000 milliseconds (1 second).

For more details, see the MDN documentation for setInterval.

Andrew Burgess
  • 1,765
  • 17
  • 19
  • This code can produce inaccurate values because it does not take into consideration possible delay of callback invocation. – jkordas May 12 '16 at 13:08
  • Good point. I went for a really basic example, because of the "Very Inexperienced" comment, but I'll upvote the other answer. – Andrew Burgess May 12 '16 at 13:11
8

My answer is similar to the one above but I'll give it anyway. This will only work on a single page so hopefully your site already runs on AJAX.

window.setInterval((function(){
   var start = Date.now();
   var textNode = document.createTextNode('0');
   document.getElementById('seconds').appendChild(textNode);
   return function() {
        textNode.data = Math.floor((Date.now()-start)/1000);
        };
   }()), 1000);
You've been on this page for <span id=seconds></span> seconds.
Jonathan Gray
  • 2,509
  • 15
  • 20
  • 1
    This code is more accurate because it takes into consideration possible delay of callback invocation. – jkordas May 12 '16 at 13:06