Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.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,这可能吗?我想在不同的时间间隔使用相同的函数。如何使函数以5000运行并执行函数中的某些代码部分 下面是一个示例,给出一个想法: var moto = function(){ // at 5000 run this part of code console.log("did stuff when called at 5000 time interval") // at 6000 run this part of code console.log("did stuff

这可能吗?我想在不同的时间间隔使用相同的函数。如何使函数以5000运行并执行函数中的某些代码部分

下面是一个示例,给出一个想法:

 var moto = function(){
   // at 5000 run this part of code
   console.log("did stuff when called at 5000 time interval")

   // at 6000 run this part of code
   console.log("did stuff when called at 6000 time interval")
 }

 window.setInterval(moto, 5000)
 window.setInterval(moto, 6000)

因此,在调用时传递一个参数

 var moto = function( val){
   if(val===5000) {
     // at 5000 run this part of code
     console.log("did stuff when called at 5000 time interval");
   } else {
   // at 6000 run this part of code
     console.log("did stuff when called at 6000 time interval");
   }
 }

 window.setInterval(moto.bind(this, 5000), 5000);
 window.setInterval(moto.bind(this, 6000), 6000);

一种方法是向函数传递一些参数,如:

var moto = function(runAt){
   // at 5000 run this part of code
   if(runAt==500)
   console.log("did stuff when called at 5000 time interval")

   // at 6000 run this part of code
   if(runAt==600)
   console.log("did stuff when called at 6000 time interval")
 }

 window.setInterval(function() {moto(500)}, 5000)
 window.setInterval(function() {moto(600)}, 6000)

如果确实希望它是相同的函数,请设置所需延迟的最大公约数的延迟,在本例中为gcd5000,6000=1000。然后使用计数器

var计数器=0; var moto=函数{ ++计数器; 如果计数器%5==0//5000运行这部分代码 以5000时间间隔调用console.logdid 如果计数器%6==0//6000运行这部分代码 在6000时间间隔调用console.logdid时 };
window.setIntervalmoto,1000 另一种做事方式:p

摩托级{ 施工期{ 这个.延迟=延迟 setIntervalthis.fn.bindthis,延迟 } fn{ //在5000时运行这部分代码 如果此值为0.delay==5000 以5000时间间隔调用console.logdid //在6000时运行这部分代码 如果此值为0.delay==6000 在6000时间间隔调用console.logdid时 } } 新Moto5000
新的摩托6000,它能跑吗once@epascarello现在它看起来不再像你的了。当它达到最不常见的延迟倍数时,你可以重置计数器。