在我的网站上,我想要计算(并显示)用户已经在我的网站上停留了多少秒钟(而不是分钟或小时)。所以,如果他们在网站上停留了5分钟,它将显示300,而不是5分钟。对于JavaScript我十分不熟练,请求帮助。
在我的网站上,我想要计算(并显示)用户已经在我的网站上停留了多少秒钟(而不是分钟或小时)。所以,如果他们在网站上停留了5分钟,它将显示300,而不是5分钟。对于JavaScript我十分不熟练,请求帮助。
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>
如果您运行此代码片段,您将看到计数器在工作。
setInterval
函数需要两个参数:
由于您想每秒钟增加一次计数器,因此要使用1000毫秒(1秒)。
有关更多详细信息,请参阅MDN对setInterval
的文档。
我的回答与上面的类似,但我还是会给出。这只适用于单个页面,希望你的网站已经在使用 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.