Javascript 第二个计数器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37187504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:00:52  来源:igfitidea点击:

Javascript Second Counter

javascriptcounter

提问by JaredCBarnes

On my website, I am trying to count (and display) how many seconds (not minutes or hours) the user has been on my site. So, if they have been on it for 5 minutes, it will display 300, Not 5 minutes. I am Very Unexperienced with JavaScript, So please help.

在我的网站上,我试图计算(并显示)用户在我的网站上停留了多少秒(不是分钟或小时)。所以,如果他们已经使用了 5 分钟,它会显示 300,而不是 5 分钟。我对 JavaScript 非常缺乏经验,所以请帮忙。

回答by Andrew Burgess

You can use the setIntervalfunction to run another function as often as you choose. For example:

您可以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>

If you run this snippet, you'll see the counter working.

如果您运行此代码段,您将看到计数器在工作。

The setIntervalfunction takes two parameters:

setInterval函数有两个参数:

  • the function you want to call
  • the number of milliseconds between calls
  • 你要调用的函数
  • 调用之间的毫秒数

Since you want to call increment the counter every second, you want to use 1000 milliseconds (1 second).

由于您希望每秒调用 increment 计数器,因此您希望使用 1000 毫秒(1 秒)。

For more details, see the MDN documentation for setInterval.

有关更多详细信息,请参阅MDN 文档setInterval

回答by Jonathan Gray

My answer is similar to the one above but I'll give it anyway. This will only work on a single page so hopefully your site already runs on AJAX.

我的答案与上面的相似,但无论如何我都会给出。这仅适用于单个页面,因此希望您的网站已经在 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.