【发布时间】:2016-09-08 07:44:38
【问题描述】:
在我的网站上,我试图计算(并显示)用户在我的网站上停留了多少秒(不是几分钟或几小时)。所以,如果他们已经在上面呆了 5 分钟,它会显示 300,而不是 5 分钟。 我对 JavaScript 非常陌生,所以请帮忙。
【问题讨论】:
-
转到此链接并查看类似问题:stackoverflow.com/questions/5517597/…
标签: javascript counter
在我的网站上,我试图计算(并显示)用户在我的网站上停留了多少秒(不是几分钟或几小时)。所以,如果他们已经在上面呆了 5 分钟,它会显示 300,而不是 5 分钟。 我对 JavaScript 非常陌生,所以请帮忙。
【问题讨论】:
标签: javascript counter
我的答案与上面的类似,但无论如何我都会给出。这仅适用于单个页面,因此希望您的网站已经在 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.
【讨论】:
您可以使用setInterval 函数根据您的选择频繁地运行另一个函数。例如:
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>
如果你运行这个 sn-p,你会看到计数器在工作。
setInterval 函数有两个参数:
由于您希望每秒调用递增计数器,因此您希望使用 1000 毫秒(1 秒)。
更多详情,请参阅MDN documentation for setInterval。
【讨论】: