How to call function at fixed interval with ensuring previous function is completed












1















I have a Promise based function which i want to call at fixed interval, Lets say at every 60 seconds. But i also want to make sure that function is called only if the previously called function is executed completely and i want to continue this for infinite time



function fun(){
return new Promise((resolve,reject)=>{
//Some database queries which may or may not complete in 60 seconds
resolve("done")
})
}

setInterval(()=>{
fun().then(d=>{
console.log(d)
})
},60000)


Above code will not check for previously called function is completed or not. but i want to make sure that










share|improve this question




















  • 3





    If you want to wait until it's completed then you should switch to setTimeout instead

    – Icepickle
    Jan 3 at 12:24











  • Just use setTimeout instead of setInterval, and call again.

    – Keith
    Jan 3 at 12:24











  • Use a global variable to keep track whether fun is executing. Set it to true when it's called, set it to false when the promise is resolved. If the flag is truthy, don't call fun in the interval, otherwise, call it. Otherwise, if you don't mind about timing, just a use setTimeout instead. Besides, there is no async await in your code, is it indended? (it's tagged)

    – briosheje
    Jan 3 at 12:25













  • @briosheje Do be aware doing that though, you might then have to wait nearly 2 mins before the next check, or the next check might happen instantly after the last.

    – Keith
    Jan 3 at 12:26













  • @Icepickle OP wants it to run every 60 seconds, for infinite time.

    – Mirakurun
    Jan 3 at 12:26
















1















I have a Promise based function which i want to call at fixed interval, Lets say at every 60 seconds. But i also want to make sure that function is called only if the previously called function is executed completely and i want to continue this for infinite time



function fun(){
return new Promise((resolve,reject)=>{
//Some database queries which may or may not complete in 60 seconds
resolve("done")
})
}

setInterval(()=>{
fun().then(d=>{
console.log(d)
})
},60000)


Above code will not check for previously called function is completed or not. but i want to make sure that










share|improve this question




















  • 3





    If you want to wait until it's completed then you should switch to setTimeout instead

    – Icepickle
    Jan 3 at 12:24











  • Just use setTimeout instead of setInterval, and call again.

    – Keith
    Jan 3 at 12:24











  • Use a global variable to keep track whether fun is executing. Set it to true when it's called, set it to false when the promise is resolved. If the flag is truthy, don't call fun in the interval, otherwise, call it. Otherwise, if you don't mind about timing, just a use setTimeout instead. Besides, there is no async await in your code, is it indended? (it's tagged)

    – briosheje
    Jan 3 at 12:25













  • @briosheje Do be aware doing that though, you might then have to wait nearly 2 mins before the next check, or the next check might happen instantly after the last.

    – Keith
    Jan 3 at 12:26













  • @Icepickle OP wants it to run every 60 seconds, for infinite time.

    – Mirakurun
    Jan 3 at 12:26














1












1








1


1






I have a Promise based function which i want to call at fixed interval, Lets say at every 60 seconds. But i also want to make sure that function is called only if the previously called function is executed completely and i want to continue this for infinite time



function fun(){
return new Promise((resolve,reject)=>{
//Some database queries which may or may not complete in 60 seconds
resolve("done")
})
}

setInterval(()=>{
fun().then(d=>{
console.log(d)
})
},60000)


Above code will not check for previously called function is completed or not. but i want to make sure that










share|improve this question
















I have a Promise based function which i want to call at fixed interval, Lets say at every 60 seconds. But i also want to make sure that function is called only if the previously called function is executed completely and i want to continue this for infinite time



function fun(){
return new Promise((resolve,reject)=>{
//Some database queries which may or may not complete in 60 seconds
resolve("done")
})
}

setInterval(()=>{
fun().then(d=>{
console.log(d)
})
},60000)


Above code will not check for previously called function is completed or not. but i want to make sure that







javascript node.js promise async-await settimeinterval






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 13:07







Krunal Sonparate

















asked Jan 3 at 12:22









Krunal SonparateKrunal Sonparate

179215




179215








  • 3





    If you want to wait until it's completed then you should switch to setTimeout instead

    – Icepickle
    Jan 3 at 12:24











  • Just use setTimeout instead of setInterval, and call again.

    – Keith
    Jan 3 at 12:24











  • Use a global variable to keep track whether fun is executing. Set it to true when it's called, set it to false when the promise is resolved. If the flag is truthy, don't call fun in the interval, otherwise, call it. Otherwise, if you don't mind about timing, just a use setTimeout instead. Besides, there is no async await in your code, is it indended? (it's tagged)

    – briosheje
    Jan 3 at 12:25













  • @briosheje Do be aware doing that though, you might then have to wait nearly 2 mins before the next check, or the next check might happen instantly after the last.

    – Keith
    Jan 3 at 12:26













  • @Icepickle OP wants it to run every 60 seconds, for infinite time.

    – Mirakurun
    Jan 3 at 12:26














  • 3





    If you want to wait until it's completed then you should switch to setTimeout instead

    – Icepickle
    Jan 3 at 12:24











  • Just use setTimeout instead of setInterval, and call again.

    – Keith
    Jan 3 at 12:24











  • Use a global variable to keep track whether fun is executing. Set it to true when it's called, set it to false when the promise is resolved. If the flag is truthy, don't call fun in the interval, otherwise, call it. Otherwise, if you don't mind about timing, just a use setTimeout instead. Besides, there is no async await in your code, is it indended? (it's tagged)

    – briosheje
    Jan 3 at 12:25













  • @briosheje Do be aware doing that though, you might then have to wait nearly 2 mins before the next check, or the next check might happen instantly after the last.

    – Keith
    Jan 3 at 12:26













  • @Icepickle OP wants it to run every 60 seconds, for infinite time.

    – Mirakurun
    Jan 3 at 12:26








3




3





If you want to wait until it's completed then you should switch to setTimeout instead

– Icepickle
Jan 3 at 12:24





If you want to wait until it's completed then you should switch to setTimeout instead

– Icepickle
Jan 3 at 12:24













Just use setTimeout instead of setInterval, and call again.

– Keith
Jan 3 at 12:24





Just use setTimeout instead of setInterval, and call again.

– Keith
Jan 3 at 12:24













Use a global variable to keep track whether fun is executing. Set it to true when it's called, set it to false when the promise is resolved. If the flag is truthy, don't call fun in the interval, otherwise, call it. Otherwise, if you don't mind about timing, just a use setTimeout instead. Besides, there is no async await in your code, is it indended? (it's tagged)

– briosheje
Jan 3 at 12:25







Use a global variable to keep track whether fun is executing. Set it to true when it's called, set it to false when the promise is resolved. If the flag is truthy, don't call fun in the interval, otherwise, call it. Otherwise, if you don't mind about timing, just a use setTimeout instead. Besides, there is no async await in your code, is it indended? (it's tagged)

– briosheje
Jan 3 at 12:25















@briosheje Do be aware doing that though, you might then have to wait nearly 2 mins before the next check, or the next check might happen instantly after the last.

– Keith
Jan 3 at 12:26







@briosheje Do be aware doing that though, you might then have to wait nearly 2 mins before the next check, or the next check might happen instantly after the last.

– Keith
Jan 3 at 12:26















@Icepickle OP wants it to run every 60 seconds, for infinite time.

– Mirakurun
Jan 3 at 12:26





@Icepickle OP wants it to run every 60 seconds, for infinite time.

– Mirakurun
Jan 3 at 12:26












3 Answers
3






active

oldest

votes


















2

















class AsyncQueue {
constructor() {
this.queue = null;
}

push(task) {
// If we have task in query, append new at the end, if not execute immediately
// Every task appended to existing queue will be executed immediately after previous one is finished
return this.queue = this.queue ? this.queue.then(() => task()) : task();
}
}

const task = (id) => () => new Promise((resolve) => {
console.log('Task', id, 'started');
// Random time betwen 500-1300ms
const time = Math.round(Math.random() * 800 + 500);
setTimeout(() => {
console.log("Finished task '" + id + "' after " + time + "ms");
resolve();
}, time);
});
const queue = new AsyncQueue();
let id = 0;
// This will push new task to queue every 1s
setInterval(() => {
console.log("Pushing new task", ++id);
queue.push(task(id));
}, 1000);





Of course we can implement it without using class



let queue;
function push(task) {
return queue = queue ? queue.then(() => task()) : task();
}
// or
const push = (task) => queue = queue ? queue.then(() => task()) : task();





share|improve this answer


























  • Nice solution :)

    – Icepickle
    Jan 3 at 20:36











  • @Icepickle thanks, I don't like to complicate things

    – ponury-kostek
    Jan 4 at 9:07











  • @ponury-kostek Thanks for the solution :)

    – Krunal Sonparate
    Jan 4 at 14:19











  • @KrunalSonparate you welcome :)

    – ponury-kostek
    Jan 4 at 14:20



















1














Instead of calling the function in setInterval call it with setTimeout after response is received.






function fun(){
return new Promise((resolve,reject)=>{
//Some database queries which may or may not complete in 60 seconds
resolve("done")
})
}
//Function to call promise function recursively
function functionCaller(fn){
fn()
.then((response)=>{
console.log(response)
setTimeout(() => functionCaller(fn), 6000)
})
}

functionCaller(fun)








share|improve this answer































    1














    Well, if you want to wait until it has finished, you should call it again after the promise has resolved. So you would then change from setInterval to setTimeout instead.



    For the purpose of this question, I did change the timeout to 1 second instead






    function fun(){
    return new Promise((resolve,reject)=>{
    //Some database queries which may or may not complete in 60 seconds
    resolve("done")
    })
    }

    function self() {
    setTimeout(()=>{
    fun().then(d=>{
    console.log(d)
    }).then( self ); // call the setTimeout function again
    },1000);
    }

    self();





    Of course, choose a better name than self, it was like the only thing I could come up with on short notice :)



    Update



    I think I misunderstood the question originally, so you only want to call it again if it really did complete, and not wait until it finished and then have the new interval start.



    In that case, you can rather do something like this instead:






    function fun(){
    fun.running = true;
    return new Promise((resolve,reject)=>{
    //Some database queries which may or may not complete in 60 seconds
    resolve("done");
    });
    }

    setInterval(()=>{
    // just make sure the fun isn't running
    if (!fun.running) {
    fun()
    .then(d=> console.log(d) )
    .catch( err => console.log( err ) ) // error handling here to make sure the next block is run
    .then( () => {
    // and handle the reset of the flag here
    fun.running = false;
    } );
    }
    },1000);








    share|improve this answer


























    • This solution will not work for me. It will add time of execution of that function also so it will not called at every 1000 ms

      – Krunal Sonparate
      Jan 3 at 12:32











    • @KrunalSonparate Sorry, I believe I misunderstood your initial question, but I have updated my answer to mark it using a flag on the function

      – Icepickle
      Jan 3 at 12:41












    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54022223%2fhow-to-call-function-at-fixed-interval-with-ensuring-previous-function-is-comple%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2

















    class AsyncQueue {
    constructor() {
    this.queue = null;
    }

    push(task) {
    // If we have task in query, append new at the end, if not execute immediately
    // Every task appended to existing queue will be executed immediately after previous one is finished
    return this.queue = this.queue ? this.queue.then(() => task()) : task();
    }
    }

    const task = (id) => () => new Promise((resolve) => {
    console.log('Task', id, 'started');
    // Random time betwen 500-1300ms
    const time = Math.round(Math.random() * 800 + 500);
    setTimeout(() => {
    console.log("Finished task '" + id + "' after " + time + "ms");
    resolve();
    }, time);
    });
    const queue = new AsyncQueue();
    let id = 0;
    // This will push new task to queue every 1s
    setInterval(() => {
    console.log("Pushing new task", ++id);
    queue.push(task(id));
    }, 1000);





    Of course we can implement it without using class



    let queue;
    function push(task) {
    return queue = queue ? queue.then(() => task()) : task();
    }
    // or
    const push = (task) => queue = queue ? queue.then(() => task()) : task();





    share|improve this answer


























    • Nice solution :)

      – Icepickle
      Jan 3 at 20:36











    • @Icepickle thanks, I don't like to complicate things

      – ponury-kostek
      Jan 4 at 9:07











    • @ponury-kostek Thanks for the solution :)

      – Krunal Sonparate
      Jan 4 at 14:19











    • @KrunalSonparate you welcome :)

      – ponury-kostek
      Jan 4 at 14:20
















    2

















    class AsyncQueue {
    constructor() {
    this.queue = null;
    }

    push(task) {
    // If we have task in query, append new at the end, if not execute immediately
    // Every task appended to existing queue will be executed immediately after previous one is finished
    return this.queue = this.queue ? this.queue.then(() => task()) : task();
    }
    }

    const task = (id) => () => new Promise((resolve) => {
    console.log('Task', id, 'started');
    // Random time betwen 500-1300ms
    const time = Math.round(Math.random() * 800 + 500);
    setTimeout(() => {
    console.log("Finished task '" + id + "' after " + time + "ms");
    resolve();
    }, time);
    });
    const queue = new AsyncQueue();
    let id = 0;
    // This will push new task to queue every 1s
    setInterval(() => {
    console.log("Pushing new task", ++id);
    queue.push(task(id));
    }, 1000);





    Of course we can implement it without using class



    let queue;
    function push(task) {
    return queue = queue ? queue.then(() => task()) : task();
    }
    // or
    const push = (task) => queue = queue ? queue.then(() => task()) : task();





    share|improve this answer


























    • Nice solution :)

      – Icepickle
      Jan 3 at 20:36











    • @Icepickle thanks, I don't like to complicate things

      – ponury-kostek
      Jan 4 at 9:07











    • @ponury-kostek Thanks for the solution :)

      – Krunal Sonparate
      Jan 4 at 14:19











    • @KrunalSonparate you welcome :)

      – ponury-kostek
      Jan 4 at 14:20














    2












    2








    2










    class AsyncQueue {
    constructor() {
    this.queue = null;
    }

    push(task) {
    // If we have task in query, append new at the end, if not execute immediately
    // Every task appended to existing queue will be executed immediately after previous one is finished
    return this.queue = this.queue ? this.queue.then(() => task()) : task();
    }
    }

    const task = (id) => () => new Promise((resolve) => {
    console.log('Task', id, 'started');
    // Random time betwen 500-1300ms
    const time = Math.round(Math.random() * 800 + 500);
    setTimeout(() => {
    console.log("Finished task '" + id + "' after " + time + "ms");
    resolve();
    }, time);
    });
    const queue = new AsyncQueue();
    let id = 0;
    // This will push new task to queue every 1s
    setInterval(() => {
    console.log("Pushing new task", ++id);
    queue.push(task(id));
    }, 1000);





    Of course we can implement it without using class



    let queue;
    function push(task) {
    return queue = queue ? queue.then(() => task()) : task();
    }
    // or
    const push = (task) => queue = queue ? queue.then(() => task()) : task();





    share|improve this answer


















    class AsyncQueue {
    constructor() {
    this.queue = null;
    }

    push(task) {
    // If we have task in query, append new at the end, if not execute immediately
    // Every task appended to existing queue will be executed immediately after previous one is finished
    return this.queue = this.queue ? this.queue.then(() => task()) : task();
    }
    }

    const task = (id) => () => new Promise((resolve) => {
    console.log('Task', id, 'started');
    // Random time betwen 500-1300ms
    const time = Math.round(Math.random() * 800 + 500);
    setTimeout(() => {
    console.log("Finished task '" + id + "' after " + time + "ms");
    resolve();
    }, time);
    });
    const queue = new AsyncQueue();
    let id = 0;
    // This will push new task to queue every 1s
    setInterval(() => {
    console.log("Pushing new task", ++id);
    queue.push(task(id));
    }, 1000);





    Of course we can implement it without using class



    let queue;
    function push(task) {
    return queue = queue ? queue.then(() => task()) : task();
    }
    // or
    const push = (task) => queue = queue ? queue.then(() => task()) : task();





    class AsyncQueue {
    constructor() {
    this.queue = null;
    }

    push(task) {
    // If we have task in query, append new at the end, if not execute immediately
    // Every task appended to existing queue will be executed immediately after previous one is finished
    return this.queue = this.queue ? this.queue.then(() => task()) : task();
    }
    }

    const task = (id) => () => new Promise((resolve) => {
    console.log('Task', id, 'started');
    // Random time betwen 500-1300ms
    const time = Math.round(Math.random() * 800 + 500);
    setTimeout(() => {
    console.log("Finished task '" + id + "' after " + time + "ms");
    resolve();
    }, time);
    });
    const queue = new AsyncQueue();
    let id = 0;
    // This will push new task to queue every 1s
    setInterval(() => {
    console.log("Pushing new task", ++id);
    queue.push(task(id));
    }, 1000);





    class AsyncQueue {
    constructor() {
    this.queue = null;
    }

    push(task) {
    // If we have task in query, append new at the end, if not execute immediately
    // Every task appended to existing queue will be executed immediately after previous one is finished
    return this.queue = this.queue ? this.queue.then(() => task()) : task();
    }
    }

    const task = (id) => () => new Promise((resolve) => {
    console.log('Task', id, 'started');
    // Random time betwen 500-1300ms
    const time = Math.round(Math.random() * 800 + 500);
    setTimeout(() => {
    console.log("Finished task '" + id + "' after " + time + "ms");
    resolve();
    }, time);
    });
    const queue = new AsyncQueue();
    let id = 0;
    // This will push new task to queue every 1s
    setInterval(() => {
    console.log("Pushing new task", ++id);
    queue.push(task(id));
    }, 1000);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 10 at 13:40

























    answered Jan 3 at 16:02









    ponury-kostekponury-kostek

    4,81741224




    4,81741224













    • Nice solution :)

      – Icepickle
      Jan 3 at 20:36











    • @Icepickle thanks, I don't like to complicate things

      – ponury-kostek
      Jan 4 at 9:07











    • @ponury-kostek Thanks for the solution :)

      – Krunal Sonparate
      Jan 4 at 14:19











    • @KrunalSonparate you welcome :)

      – ponury-kostek
      Jan 4 at 14:20



















    • Nice solution :)

      – Icepickle
      Jan 3 at 20:36











    • @Icepickle thanks, I don't like to complicate things

      – ponury-kostek
      Jan 4 at 9:07











    • @ponury-kostek Thanks for the solution :)

      – Krunal Sonparate
      Jan 4 at 14:19











    • @KrunalSonparate you welcome :)

      – ponury-kostek
      Jan 4 at 14:20

















    Nice solution :)

    – Icepickle
    Jan 3 at 20:36





    Nice solution :)

    – Icepickle
    Jan 3 at 20:36













    @Icepickle thanks, I don't like to complicate things

    – ponury-kostek
    Jan 4 at 9:07





    @Icepickle thanks, I don't like to complicate things

    – ponury-kostek
    Jan 4 at 9:07













    @ponury-kostek Thanks for the solution :)

    – Krunal Sonparate
    Jan 4 at 14:19





    @ponury-kostek Thanks for the solution :)

    – Krunal Sonparate
    Jan 4 at 14:19













    @KrunalSonparate you welcome :)

    – ponury-kostek
    Jan 4 at 14:20





    @KrunalSonparate you welcome :)

    – ponury-kostek
    Jan 4 at 14:20













    1














    Instead of calling the function in setInterval call it with setTimeout after response is received.






    function fun(){
    return new Promise((resolve,reject)=>{
    //Some database queries which may or may not complete in 60 seconds
    resolve("done")
    })
    }
    //Function to call promise function recursively
    function functionCaller(fn){
    fn()
    .then((response)=>{
    console.log(response)
    setTimeout(() => functionCaller(fn), 6000)
    })
    }

    functionCaller(fun)








    share|improve this answer




























      1














      Instead of calling the function in setInterval call it with setTimeout after response is received.






      function fun(){
      return new Promise((resolve,reject)=>{
      //Some database queries which may or may not complete in 60 seconds
      resolve("done")
      })
      }
      //Function to call promise function recursively
      function functionCaller(fn){
      fn()
      .then((response)=>{
      console.log(response)
      setTimeout(() => functionCaller(fn), 6000)
      })
      }

      functionCaller(fun)








      share|improve this answer


























        1












        1








        1







        Instead of calling the function in setInterval call it with setTimeout after response is received.






        function fun(){
        return new Promise((resolve,reject)=>{
        //Some database queries which may or may not complete in 60 seconds
        resolve("done")
        })
        }
        //Function to call promise function recursively
        function functionCaller(fn){
        fn()
        .then((response)=>{
        console.log(response)
        setTimeout(() => functionCaller(fn), 6000)
        })
        }

        functionCaller(fun)








        share|improve this answer













        Instead of calling the function in setInterval call it with setTimeout after response is received.






        function fun(){
        return new Promise((resolve,reject)=>{
        //Some database queries which may or may not complete in 60 seconds
        resolve("done")
        })
        }
        //Function to call promise function recursively
        function functionCaller(fn){
        fn()
        .then((response)=>{
        console.log(response)
        setTimeout(() => functionCaller(fn), 6000)
        })
        }

        functionCaller(fun)








        function fun(){
        return new Promise((resolve,reject)=>{
        //Some database queries which may or may not complete in 60 seconds
        resolve("done")
        })
        }
        //Function to call promise function recursively
        function functionCaller(fn){
        fn()
        .then((response)=>{
        console.log(response)
        setTimeout(() => functionCaller(fn), 6000)
        })
        }

        functionCaller(fun)





        function fun(){
        return new Promise((resolve,reject)=>{
        //Some database queries which may or may not complete in 60 seconds
        resolve("done")
        })
        }
        //Function to call promise function recursively
        function functionCaller(fn){
        fn()
        .then((response)=>{
        console.log(response)
        setTimeout(() => functionCaller(fn), 6000)
        })
        }

        functionCaller(fun)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 3 at 12:29









        AshishAshish

        817624




        817624























            1














            Well, if you want to wait until it has finished, you should call it again after the promise has resolved. So you would then change from setInterval to setTimeout instead.



            For the purpose of this question, I did change the timeout to 1 second instead






            function fun(){
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done")
            })
            }

            function self() {
            setTimeout(()=>{
            fun().then(d=>{
            console.log(d)
            }).then( self ); // call the setTimeout function again
            },1000);
            }

            self();





            Of course, choose a better name than self, it was like the only thing I could come up with on short notice :)



            Update



            I think I misunderstood the question originally, so you only want to call it again if it really did complete, and not wait until it finished and then have the new interval start.



            In that case, you can rather do something like this instead:






            function fun(){
            fun.running = true;
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done");
            });
            }

            setInterval(()=>{
            // just make sure the fun isn't running
            if (!fun.running) {
            fun()
            .then(d=> console.log(d) )
            .catch( err => console.log( err ) ) // error handling here to make sure the next block is run
            .then( () => {
            // and handle the reset of the flag here
            fun.running = false;
            } );
            }
            },1000);








            share|improve this answer


























            • This solution will not work for me. It will add time of execution of that function also so it will not called at every 1000 ms

              – Krunal Sonparate
              Jan 3 at 12:32











            • @KrunalSonparate Sorry, I believe I misunderstood your initial question, but I have updated my answer to mark it using a flag on the function

              – Icepickle
              Jan 3 at 12:41
















            1














            Well, if you want to wait until it has finished, you should call it again after the promise has resolved. So you would then change from setInterval to setTimeout instead.



            For the purpose of this question, I did change the timeout to 1 second instead






            function fun(){
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done")
            })
            }

            function self() {
            setTimeout(()=>{
            fun().then(d=>{
            console.log(d)
            }).then( self ); // call the setTimeout function again
            },1000);
            }

            self();





            Of course, choose a better name than self, it was like the only thing I could come up with on short notice :)



            Update



            I think I misunderstood the question originally, so you only want to call it again if it really did complete, and not wait until it finished and then have the new interval start.



            In that case, you can rather do something like this instead:






            function fun(){
            fun.running = true;
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done");
            });
            }

            setInterval(()=>{
            // just make sure the fun isn't running
            if (!fun.running) {
            fun()
            .then(d=> console.log(d) )
            .catch( err => console.log( err ) ) // error handling here to make sure the next block is run
            .then( () => {
            // and handle the reset of the flag here
            fun.running = false;
            } );
            }
            },1000);








            share|improve this answer


























            • This solution will not work for me. It will add time of execution of that function also so it will not called at every 1000 ms

              – Krunal Sonparate
              Jan 3 at 12:32











            • @KrunalSonparate Sorry, I believe I misunderstood your initial question, but I have updated my answer to mark it using a flag on the function

              – Icepickle
              Jan 3 at 12:41














            1












            1








            1







            Well, if you want to wait until it has finished, you should call it again after the promise has resolved. So you would then change from setInterval to setTimeout instead.



            For the purpose of this question, I did change the timeout to 1 second instead






            function fun(){
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done")
            })
            }

            function self() {
            setTimeout(()=>{
            fun().then(d=>{
            console.log(d)
            }).then( self ); // call the setTimeout function again
            },1000);
            }

            self();





            Of course, choose a better name than self, it was like the only thing I could come up with on short notice :)



            Update



            I think I misunderstood the question originally, so you only want to call it again if it really did complete, and not wait until it finished and then have the new interval start.



            In that case, you can rather do something like this instead:






            function fun(){
            fun.running = true;
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done");
            });
            }

            setInterval(()=>{
            // just make sure the fun isn't running
            if (!fun.running) {
            fun()
            .then(d=> console.log(d) )
            .catch( err => console.log( err ) ) // error handling here to make sure the next block is run
            .then( () => {
            // and handle the reset of the flag here
            fun.running = false;
            } );
            }
            },1000);








            share|improve this answer















            Well, if you want to wait until it has finished, you should call it again after the promise has resolved. So you would then change from setInterval to setTimeout instead.



            For the purpose of this question, I did change the timeout to 1 second instead






            function fun(){
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done")
            })
            }

            function self() {
            setTimeout(()=>{
            fun().then(d=>{
            console.log(d)
            }).then( self ); // call the setTimeout function again
            },1000);
            }

            self();





            Of course, choose a better name than self, it was like the only thing I could come up with on short notice :)



            Update



            I think I misunderstood the question originally, so you only want to call it again if it really did complete, and not wait until it finished and then have the new interval start.



            In that case, you can rather do something like this instead:






            function fun(){
            fun.running = true;
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done");
            });
            }

            setInterval(()=>{
            // just make sure the fun isn't running
            if (!fun.running) {
            fun()
            .then(d=> console.log(d) )
            .catch( err => console.log( err ) ) // error handling here to make sure the next block is run
            .then( () => {
            // and handle the reset of the flag here
            fun.running = false;
            } );
            }
            },1000);








            function fun(){
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done")
            })
            }

            function self() {
            setTimeout(()=>{
            fun().then(d=>{
            console.log(d)
            }).then( self ); // call the setTimeout function again
            },1000);
            }

            self();





            function fun(){
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done")
            })
            }

            function self() {
            setTimeout(()=>{
            fun().then(d=>{
            console.log(d)
            }).then( self ); // call the setTimeout function again
            },1000);
            }

            self();





            function fun(){
            fun.running = true;
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done");
            });
            }

            setInterval(()=>{
            // just make sure the fun isn't running
            if (!fun.running) {
            fun()
            .then(d=> console.log(d) )
            .catch( err => console.log( err ) ) // error handling here to make sure the next block is run
            .then( () => {
            // and handle the reset of the flag here
            fun.running = false;
            } );
            }
            },1000);





            function fun(){
            fun.running = true;
            return new Promise((resolve,reject)=>{
            //Some database queries which may or may not complete in 60 seconds
            resolve("done");
            });
            }

            setInterval(()=>{
            // just make sure the fun isn't running
            if (!fun.running) {
            fun()
            .then(d=> console.log(d) )
            .catch( err => console.log( err ) ) // error handling here to make sure the next block is run
            .then( () => {
            // and handle the reset of the flag here
            fun.running = false;
            } );
            }
            },1000);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 3 at 12:40

























            answered Jan 3 at 12:27









            IcepickleIcepickle

            8,97732237




            8,97732237













            • This solution will not work for me. It will add time of execution of that function also so it will not called at every 1000 ms

              – Krunal Sonparate
              Jan 3 at 12:32











            • @KrunalSonparate Sorry, I believe I misunderstood your initial question, but I have updated my answer to mark it using a flag on the function

              – Icepickle
              Jan 3 at 12:41



















            • This solution will not work for me. It will add time of execution of that function also so it will not called at every 1000 ms

              – Krunal Sonparate
              Jan 3 at 12:32











            • @KrunalSonparate Sorry, I believe I misunderstood your initial question, but I have updated my answer to mark it using a flag on the function

              – Icepickle
              Jan 3 at 12:41

















            This solution will not work for me. It will add time of execution of that function also so it will not called at every 1000 ms

            – Krunal Sonparate
            Jan 3 at 12:32





            This solution will not work for me. It will add time of execution of that function also so it will not called at every 1000 ms

            – Krunal Sonparate
            Jan 3 at 12:32













            @KrunalSonparate Sorry, I believe I misunderstood your initial question, but I have updated my answer to mark it using a flag on the function

            – Icepickle
            Jan 3 at 12:41





            @KrunalSonparate Sorry, I believe I misunderstood your initial question, but I have updated my answer to mark it using a flag on the function

            – Icepickle
            Jan 3 at 12:41


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54022223%2fhow-to-call-function-at-fixed-interval-with-ensuring-previous-function-is-comple%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas

            Can't read property showImagePicker of undefined in react native iOS