usersam
usersam

Reputation: 1235

javascript - how to control setinterval internal

In my application development, I am using

setInterval(function() {
  // some code
  // runs here
}, 60000);

I want to execute some code on 1 minute interval and my code may take 2-3 minutes in some cases.

<execute code> - <wait 1 minute> - <execute code> - <wait 1 minute> ......so on

I tried with setInterval function but noticed that setInterval does not wait for inner code to complete. Please suggest how can i achieve this in javascript.

Thanks

Upvotes: 0

Views: 111

Answers (3)

user3366943
user3366943

Reputation: 263

// adjust wait time to your liking
const waitTime = 10000 
let time = 0
// so you can stop it
const totalTime = 6 

function excuteCode() {
  time++;
  console.log(time);  // <=== replace with your inner code
  if (time < totalTime) {
    setTimeout(() => {
      excuteCode()
    }, waitTime)
  }
}

excuteCode();

Upvotes: 0

Mukund Goel
Mukund Goel

Reputation: 599

Something like this might work for you, but why do you have a function that takes over 1 min to return something?

let callCompleted = true;

setInterval(function() {
   if (callCompleted) {
      callCompleted = false;

      // pass a call back function to update the callCompleted to true
      myLongRunningFunction(function() { callCompleted = true } );

      // or if `myLongRunningFunction` returns a promise 
      myLongRunningFunction.then(() => { callCompleted = true } );
   } 
}, 60000);

Upvotes: 0

Federkun
Federkun

Reputation: 36924

A better way may be to recursively call your job function with setTimeout:

setTimeout(function jobThatRunEveryMinute() {
  // run code here that may take more than one minute
  someExpensiveCodeToRun()

  // start another job after someExpensiveCode completes
  setTimeout(jobThatRunEveryMinute, 60000);
}, 60000);

Upvotes: 2

Related Questions