在我的网站上,我正在尝试计算(并显示)用户在我的网站上停留了多少秒(而不是几分钟或几小时)。因此,如果他们已经使用了5分钟,它将显示300,而不是5分钟。 我对JavaScript很缺乏经验,所以请帮助。
答案 0 :(得分:11)
您可以使用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>
&#13;
如果您运行此代码段,则会看到计数器正常工作。
setInterval
函数有两个参数:
由于你想每秒调用递增计数器,你想使用1000毫秒(1秒)。
有关详细信息,请参阅MDN documentation for setInterval
。
答案 1 :(得分:4)
我的答案与上面的答案类似,但无论如何我都会给出答案。这只适用于单个页面,所以希望您的网站已经在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);
&#13;
You've been on this page for <span id=seconds></span> seconds.
&#13;