当以不同的间隔调用时,如何使相同的函数执行代码的不同部分

时间:2016-12-20 00:54:26

标签: 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 when called at 6000 time interval")
 }

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

4 个答案:

答案 0 :(得分:5)

所以通过调用传递一个参数。

 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);

答案 1 :(得分:2)

如果您确实希望它具有相同的功能,请设置所需延迟的最大公约数的延迟,在本例中为gcd(5000, 6000) = 1000。然后使用计数器。



var counter = 0;
var moto = function() {
  ++counter;
  if (counter % 5 == 0) // at 5000 run this part of code
    console.log("did stuff when called at 5000 time interval")
  if (counter % 6 == 0) // at 6000 run this part of code
    console.log("did stuff when called at 6000 time interval")
};
window.setInterval(moto, 1000);




答案 2 :(得分:0)

一种方法是将一些参数传递给你的函数,如:

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)

答案 3 :(得分:0)

寻找另一种做事方式:P

class Moto {
  constructor(delay) {
    this.delay = delay
    setInterval(this.fn.bind(this), delay)
  }
  
  fn() {
    // at 5000 run this part of code
    if (this.delay === 5000)  
      console.log("did stuff when called at 5000 time interval")
    
    // at 6000 run this part of code
    if (this.delay === 6000)
      console.log("did stuff when called at 6000 time interval")
  }
}   
   
new Moto(5000)
new Moto(6000)