3

Is it possible to send interval id to executing function as an argument ? For example some thing like this:

var id= setInterval(myFunc.bind(null,id),1000);

What I am going to do is that in myFunc I want to do some processing and clear interval if I need. I can't use global variable because it will be happened multiple time. And I know that I can use global array but it would a little a bit of time consuming because of my function logic. So I want to know if I can pass interval id as an argument to myFunc.

EDIT: this stackOverfllow link dosen't help me because there were no helpful answer.

Community
  • 1
  • 1
pouyan
  • 3,445
  • 4
  • 26
  • 44

4 Answers4

4

I use this pattern:

function myFunc(host){
   console.log(host.id);
}

var host = {};
host.id = setInterval(myFunc.bind(null,host),1000);
Tolgahan Albayrak
  • 3,118
  • 1
  • 25
  • 28
0

You could actually try mixing up setTimeout and setInterval to accomplish what you are looking for.

you could read more about setInterval on how to pass additional parameters to the functions.

var interval = 0;

function logId(param) {
  interval++;

  if (interval === 3) {
    clearInterval(param);
  }
  console.log(param);

}

var id = setInterval(function() {
  setTimeout(logId, 0, id)
}, 1000);
Sreekanth
  • 3,110
  • 10
  • 22
0

You can create your own function to store your callback function and interval id in the same object and pass that object to your interval function which will call the provided function with the interval id.

function setMyInterval(f,t) {

    var handleMyInterval = function(ob) {
        ob.func(ob.id);
    };
    var idOb = {func: f};               
    idOb.id = setInterval(handleMyInterval,t,idOb);     

    return idOb.id  
}
Ralph Ritoch
  • 3,260
  • 27
  • 37
0

You can use function inside you interval so you can do like this.

Create a function that will do interval and clear itself after a time you set.

intervalTime is time for loop interval and timeout is the time to clear interval loop.

both receive in millisecond.

function test(intervalTime,Timeout,log){
    var id = setInterval(function(){
         console.log(log)
    },intervalTime);

    setTimeout(function(){
        clearInterval(id);
    }, Timeout);
}

test(1000,10000,'test1');
test(1000,1000,'test2');
Natsathorn
  • 1,530
  • 1
  • 12
  • 26