javascript - 如何使用 JavaScript 进行计数

标签 javascript

我一直在尝试使用 JavaScript 创建计数,但它不起作用

我做到了:

function increment (){
     for (var i = 0; i <= 100;  i++){
         text.innerHTML += parseInt(i)
      }
 }

setTimeout(increment, 200)

最佳答案

如果您想要实现的话,您需要使用 setInterval 来进行实际计数:

function countUp() {
  var i = 0; // a counter which is displayed every 100ms

   // create interval which fires the callback every 100ms.
   // `interval` holds the interval ID, which is later used to clear the
   // interval (stop calling the callback)
  var interval = setInterval(function() { 

    text.innerHTML = i++; // write `i` and increment
    
    // if `i` is grater than 100 then clear the interval (stop calling the callback)
    if (i > 100) clearInterval(interval);
  }, 100);
}

countUp();
<div id="text"></div>

关于javascript - 如何使用 JavaScript 进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652080/

相关文章:

javascript - 悬停时图像变化

javascript - 在 IE 11 中覆盖 ctrl+p

javascript - 移动没有 before 伪元素的 html block

javascript - 如何自定义Gauge控件?

javascript - 阅读开源 : a series of IIFEs

javascript - PushState() 中的 StateObject 应该是什么?

javascript - jQuery 代码中 PHP 文件中的 jQuery 变量

javascript - 在同一个 app.js 中渲染来自不同 HTML 页面的多个 DOM 元素

javascript - 如何防止 Sencha Ext.Msg 在按钮单击时关闭

javascript - 将参数传递给带有变量的函数或在传递过程中进行修改