Jar*_*nes 5 javascript counter
在我的网站上,我试图计算(并显示)用户在我的网站上停留了多少秒(而不是几分钟或几小时).因此,如果他们已经使用了5分钟,它将显示300,而不是5分钟.我对JavaScript很缺乏经验,所以请帮忙.
And*_*ess 15
您可以使用该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);Run Code Online (Sandbox Code Playgroud)
<div id='seconds-counter'> </div>Run Code Online (Sandbox Code Playgroud)
如果您运行此代码段,您将看到计数器正常工作.
该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);Run Code Online (Sandbox Code Playgroud)
You've been on this page for <span id=seconds></span> seconds.Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16717 次 |
| 最近记录: |