function lemath()
{
var count;
count = 0;
stuff.innerHTML = "stuff" + count;
}
function begin()
{
lemath();
setTimeout(function() {
begin();
}, 1000);
}
我正在尝试创建一个无限循环,每次循环并显示它时都会计数,但是当我执行上面的代码时它只返回undefined? 非常感谢你的帮助! :)
答案 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();
});
答案 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)