Serhad Burakan Serhad Burakan - 1 month ago 4x
Javascript Question

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



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]) {
            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.