Alpha Wolf Gamer
Alpha Wolf Gamer

Reputation: 327

How can I postpone setInterval if a condition is met?

This is my script:

var find = setInterval(function() {
  if (document.getElementsByClassName('RDlrG Inn9w iWO5td')[0]) {
    if (document.getElementsByClassName('w1OTme')[0]) {
      window.open(document.getElementsByClassName('w1OTme')[0].href);
      //here I call the setTimeout function for my SetInterval
    }
  }
}, 2000);

This is a Tampermonkey script I am developing for Google Calendar.

I want to set a timeout function on my find function aka setInterval function so it doesn't spam the window.open function.

In short:

Is there a way I could set a Timeout function on setInterval function which is called from my setInterval function?

If yes, how so?

Upvotes: 1

Views: 495

Answers (1)

Ivar
Ivar

Reputation: 6828

You can't pause the interval of a setInterval, but you can stop it and start it again after some time.

let find = null;

function intervalFunc() {
  if (condition) {
    // Do some operations which should not be repeated for the next 30 seconds

    // Clear current interval
    clearInterval(find);
    // Schedule to start the setInterval after 30 seconds.
    setTimeout(function() {
      find = setInterval(intervalFunc, 2000);
    }, 30000 - 2000);
    //         ^
    // Subtracting the interval dalay to cancel out the delay for the first invocation.
    // (Because the first invocation will also wait for 2 seconds, so the pause would be 32 seconds instead of 30)
  }
}

// Start the initial setInterval
find = setInterval(intervalFunc, 2000);

Here is a working example:

let count = 0;

const intervalDelay = 200;
const pauseDelay = 3000;

let find = null;

function intervalFunc() {
  count++;
  console.log('check', count);

  if (count >= 5) {
    count = 0;

    console.log('Pausing for ' + (pauseDelay / 1000) + ' seconds');
    clearInterval(find);
    setTimeout(function() {
      find = setInterval(intervalFunc, intervalDelay);
    }, pauseDelay - intervalDelay);
  }
}

find = setInterval(intervalFunc, intervalDelay);

Upvotes: 1

Related Questions