Serhad Burakan
Serhad Burakan

Reputation: 37

Javascript multiple intervals with function that return promise

I have a function that return a promise. I run that function with an interval and after that promise completed interval is stopped.

I need to call this function by using an interval multiple times so there will be multiple intervals to be closed after the related promise is finished. So there will be multiple intervals running at the same time and trigger the same function.

How can I build a structure that stops the interval after its related function that return a promise is finished?

Here is a sample code that works for one interval.

function startInterval(){
    ir.intervalVariable=$interval(function() {checkFinishedJob(jobNumber}, 2000);
}

function checkFinishedJob(jobNumber){
            // check if the job which is identified with jobNumber is finished
            if(isJobfinished==true){    
                $interval.cancel(ir.intervalVariable);
            }

        }

Upvotes: 0

Views: 342

Answers (2)

Redu
Redu

Reputation: 26191

As fas as i understand there is only one setInterval to be cleared. Ok i would like to give an example. The following code has an async function which takes data and error first callback. It is promisified to become a function that takes data returns a promise. You are expected to run your callback at the then stage.

We have another function which utilizes setInterval to invoke our promisifiedAsync function with some data object like {val:0, dur:1723}. OK we also have a generator function to provide us with data. Every time a data is requested it will provide val with 1 more than previous and a random duration value between 500 - 2000.

So our intervalPromises function will produce a promise every 100ms and the earliest a promise resolves or rejects is 500 ms. So we will have at least 5 promises out there before we have a chance to stop the setInterval.

OK have a look at it.

function* generateData(){
  var i = 0;
  while (true) yield {val: i++, dur:Math.floor(Math.random()*1500)+500};
}

function promisify(fun){
  return (data) => new Promise((resolve,reject) => fun(data, (err,res) => err ? reject(err) : resolve(res)));
}

function async(data, callback){
  Math.random() < 0.5 ? setTimeout(_ => callback(false,data.val),data.dur)
                      : setTimeout(_ => callback("error at " + data.val),data.dur);
}

function myCallback(err,val){
  return err ? (console.log("failed with:", err), err)
             : (console.log("resolved with:",val), val);
}


function intervalPromises(fun, callback){
  var sid = setInterval(_ => {var data = giveMeData.next().value;
                              console.log("data to be processed asyncronously is:", data);
                              fun(data)
                              .then(val => {clearInterval(sid);
                                            callback(false,val);
                                            })
                              .catch(err => {clearInterval(sid);
                                            callback(err);
                                            });
                             }, 100);
}

var promisifiedAsync = promisify(async),
          giveMeData = generateData();
intervalPromises(promisifiedAsync,myCallback);

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 76814

Let us consider this prototype:

function IntervalFunction(params) {
    if (!IntervalFunction.intervals[params.key]) {
        IntervalFunction.intervals[params.key] = [];
    }
    IntervalFunction.intervals[params.key].push(setInterval(function() {
        if (params.executed()) {
            for (var intervalIndex in IntervalFunction.intervals[params.key]) {
                clearInterval(IntervalFunction.intervals[intervalIndex]);
            }
            IntervalFunction.intervals = [];
        }
    }, params.interval));
}
IntervalFunction.intervals = {};

Implement your callback to set a flag which is checked by params.executed() to true. That flag should be initialized by false.

Upvotes: 0

Related Questions