javascript 每 x 毫秒增加一个元素中数字的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9825286/
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-10-26 07:57:12  来源:igfitidea点击:

Increase the value of a number in an element every x milliseconds

javascriptjqueryhtml

提问by ponjoh

So I have this simple HTML:

所以我有这个简单的 HTML:

<span id="badge">0</span>

I want the number 0 to increase by 1 every x milliseconds. How do I do that with Javascript (with or without jQuery)?

我希望数字 0 每 x 毫秒增加 1。我如何使用 Javascript(有或没有 jQuery)做到这一点?

Thanks a bunch - I'm new to this :)

非常感谢 - 我是新手:)

采纳答案by Richard

You should do this:

你应该做这个:

<script>
   var $badge = $('#badge'); // cache 
   setInterval(function () {
        var value = parseInt($badge.html());
        value++;
        $badge.html(value);
   }, 1000);

</script>

Assuming 1000 milliseconds.

假设 1000 毫秒。

回答by Tom

function increment() {
    document.getElementById("badge").value = Number(document.getElementById("badge").value) + 1;
    setTimeout("increment()",3000);
}
increment()

回答by Bergi

Every of the answers I see here has the same drawbacks:

我在这里看到的每个答案都有相同的缺点:

  • performance issue because of selecting the DOM element every ms cycle. Especially when using a heavy library as jQuery.
  • setInterval()is probably the tool designed for that functionality, but not reliable. It can diverge a lot from the real time, especially when using a small interval. If you want exactly x executions per second, you may google for some timing libraries.
  • 由于每 ms 周期选择一次 DOM 元素而导致的性能问题。尤其是在使用重库作为 jQuery 时。
  • setInterval()可能是为该功能设计的工具,但不可靠。它可能与实时有很大差异,尤其是在使用小间隔时。如果你想要每秒执行 x 次,你可以在谷歌上搜索一些计时库。

I would code:

我会编码:

var textNode = document.getElementById(badge).firstChild;
var start = Date.now();
window.setInterval(function update() {
    textNode.data = Math.round((new Date()-start)/ms);
}, ms);

If you don't want to start at 0, it will be trivial to add an offset (determined before the loop begins), eg.

如果你不想从 0 开始,添加一个偏移量(在循环开始之前确定)将是微不足道的,例如。

var start = Date.now() - (textNode.data * ms || 0); // NaN catching, implicit number cast

回答by jlb

Something like this?

像这样的东西?

var millisecs = 10;
setInterval(function() {
  var $badge = $('#badge');
  $badge.text(parseInt($badge.text())++);
}, millisecs);

http://jsfiddle.net/iambriansreed/MPP8n/3/

http://jsfiddle.net/iambriansreed/MPP8n/3/

回答by Robin Delaporte

You could create a Jquery plugin, so you can reuse whenever you need.

您可以创建一个 Jquery 插件,以便您可以在需要时重复使用。

$.fn.increment= function(options) {

 var $this = $(this);

 var coef = options.coef;

 var speed = options.speed;

 var value = 0;

 setInterval(function(){ 

    value = value + coef ;

    $this.html(value);

 }, speed);

};

And in your main javascript file :

在您的主要 javascript 文件中:

$("#badge").increment({coef: 1, speed:1000});

working demo : http://jsfiddle.net/8FMZh/102/

工作演示:http: //jsfiddle.net/8FMZh/102/

回答by ShankarSangoli

You can use setInterval.

您可以使用setInterval.

var $badge = $('#badge');
setInterval(function () {
     $badge.html(parseInt($badge.html()) + 1);
}, 1);?//Specify the milliseconds here, right it will update the value every 1 millisecond

Working demo - http://jsfiddle.net/8FMZh/

工作演示 - http://jsfiddle.net/8FMZh/

回答by SpYk3HH

A little more about timers:

关于定时器的更多信息

// setting a variable for your timer will allow you the ability to "turn it on and off"
var tmrChangeI;
// setTimeout is a function to initiate a function once after given amount of milisecs
// whereas setInterval will continue a function until cancled every so many milisecs

// the following wil "turn on" your timer
tmrChangeI = setInterval(function() {
    var $badge = $('#badge');
    $badge.html($badge.html() + 1);
}, 500); // 500 will = every half of a second

// to "turn off" timer
clearInterval(tmrChangeI);

// or set a bool to test and use timeout to repeat till bool is false
var tmrBool = true;

// establish function to execute
function tmrFunc() {
    var $badge = $('#badge');
    $badge.html($badge.html() + 1);
    if (tmrBool) tmrChangeI = setTimeout(function() { tmrFunc(); }, 500); // 500 will = every half of a second
};

// execute function, begin timer
tmrChangeI = setTimeout(function() { tmrFunc(); }, 500);

// clear via bool allowing one more execution
tmrBool = false;

// clear by force possibly stoping next execution,
// tho in this manner it may be too late if timer is very short 
// and maybe overriden by bool still being true, this is not safest 
// but is example of how to use setTimeout
clearTimeout(tmrChangeI);