Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中生成每秒向变量添加一个数字的函数_Javascript - Fatal编程技术网

在Javascript中生成每秒向变量添加一个数字的函数

在Javascript中生成每秒向变量添加一个数字的函数,javascript,Javascript,基本上我想创建一个函数,每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 in

基本上我想创建一个函数,每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函数,这会随着时间的推移而变得昂贵

但是,如果你想增加每秒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函数,这会随着时间的推移而变得昂贵。

setInterval或setTimeout

setTimeout(function(){number++;},1000);


设置间隔还是设置超时

setTimeout(function(){number++;},1000);


你自己尝试过什么吗?
setInterval()
让每一秒都有事情发生
++
运算符将一个值添加到变量的值中。如果是我,我会记录你什么时候开始的。你自己尝试过什么吗?
setInterval()
,让每一秒都有事情发生
++
运算符将一个值添加到变量的值中。如果是我,我只会跟踪你开始的时间。setTimeout只执行一次,除非你在内部函数中重置超时。setTimeout只执行一次,除非你在内部函数中重置超时。好的,谢谢!我希望这将成为我想要它做的。好的,谢谢!我希望这会成为我想要它做的事情。