Friday, February 23, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  76] [ 6]  / answers: 1 / hits: 49395  / 8 Years ago, thu, may 12, 2016, 12:00:00

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.


More From » counter

 Answers
7

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.


[#62204] Tuesday, May 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
maxinec questions
;