0

Is this even possible to do? I want to use the same function at different intervals. How can I make the function run at 5000 and execute certain part of code within the function.

here is an example to give an idea:

 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 Answers 4

5

So pass a parameter with the call.

 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);
Sign up to request clarification or add additional context in comments.

Comments

2

If you really want it to be the same function, set a delay of the greatest common divisor of the desired delays, in this case gcd(5000, 6000) = 1000. And then use a counter.

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

1 Comment

You may reset the counter when it reaches the least common multiple of the delays.
0

One way would be pass some param to your functions like:

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)

2 Comments

And that runs once
@epascarello now it doesn't look like yours anymore
0

Look another way of doing things :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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.