Javascript 第二个柜台

Javascript Second Counter

在我的网站上,我试图计算(并显示)用户在我的网站上停留了多少秒(不是分钟或小时)。因此,如果他们已经使用了 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 documentation for 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.