嘿,所以基本上我想创建一个函数,每 1 秒将 1 或可变数字添加到另一个变量。
我一直在互联网上搜索这个,但一直找不到。我猜它应该相当简单。
var counter =0;
var value = 1; //the number to add. You can change it by modifying the variable
setInterval(function() {
counter+= value;
},1000);
但是,如果你想每秒增加 1 个,更有效的方法是
//set the initial value
var start = Date.now();
//create a function you can call anytime to get the diff
function getCurrentDiff() {
return (Date.now() - start)/1000;
}
那么您就不必一直运行 add 函数,这会随着时间的推移而变得昂贵。
设置间隔或设置超时?
setTimeout(function(){number++;},1000);
或者
setInterval(function(){number++;},1000);