Reputation: 115
How can I have a time counter in jQuery/JS
start ticking once a client enters my website (on page load)?
I need some sort of function etc That can calculate the amount of time the visitor stays on my website (in seconds) to be used in an if statement.
Upvotes: 1
Views: 3605
Reputation: 138297
window.onload = function(){
setInterval(count, 1000);
};
let counter = 0;
function count(){
counter++;
//do stuff
}
The count
Function is called all 1000ms=1s and increases the counter by one.
Upvotes: 0
Reputation: 34199
You can simply place the following script in the end of your document:
// 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';
};
<button>Click me</button>
Upvotes: 1