Answer the question
In order to leave comments, you need to log in
How to find out the time spent on the site in JS (with paging)?
Hello. I need to show a popup to a user who spent 1 minute on the site. He can be on one page, or flip through several pages, but the counter must count the time from entering the site (session time).
Couldn't find anything on google. Can this be done without PHP?
Answer the question
In order to leave comments, you need to log in
if (!sessionStorage.getItem('startTime')) {
sessionStorage.setItem('startTime', Date.now());
}
const enterTime = sessionStorage.getItem('startTime')
const showPopup = () => {
let currentTime = Date.now()
let spentTime = (currentTime - enterTime) / 1000
if (spentTime >= 60) {
clearInterval(timer)
alert(`Вы провели на сайте минут: ${Math.floor(spentTime / 60)}, секунд: ${Math.floor(spentTime % 60)}`)
}
}
const timer = setInterval(showPopup, 10000)
I need to show a popup to a user who spent 1 minute on the site.
1. Check localStorage, if empty - write the current time.
2. if it's not empty, but the gap is too big, consider that a "new" session has started, update the time in localStorage
3. and compare it with the current one, find out if it's time to show the popup.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question