使用Javascript创建连续计数器?

时间:2015-11-26 17:18:44

标签: javascript

function lemath()
{
    var count;
    count = 0;
    stuff.innerHTML = "stuff" + count;

}

function begin()
{
    lemath();
    setTimeout(function() {
        begin();
    }, 1000);

}

我正在尝试创建一个无限循环,每次循环并显示它时都会计数,但是当我执行上面的代码时它只返回undefined? 非常感谢你的帮助! :)

2 个答案:

答案 0 :(得分:1)

var count = 0; // declaring "count" here makes the variable globally available

function lemath()
{    
    count++;
    var stuff = document.getElementById('stuff');
    stuff.innerHTML = "stuff: " + count;
}

function begin()
{
    lemath();
    setTimeout(begin, 1000, window);
}

document.addEventListener('DOMContentLoaded', function () {    
    begin();
});

演示:http://jsfiddle.net/pottersky/jj30s2Le/1/

答案 1 :(得分:0)

您可以使用setInterval javascript方法来增加计数器


// setInterval(fn, time);

 // your counter state should be start from 0
let count = 0;

// Your function should be run each time (for example each second)
const increment = () => {
    count++
// show count in console or in DOM
    console.log(count)
    element.innerHTML = count
}

setInterval(increment, 1000);


出于性能原因以及停止或重置计时器的原因,您可以使用clearInterval方法


const timer = setInterval(increment, 1000);

 // stop counter

  clearInterval(timer)