1

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?

Ivar
  • 6,138
  • 12
  • 49
  • 61
Alpha Wolf Gamer
  • 320
  • 2
  • 12
  • "*In short: Is there a way I could set a Timeout function on setInterval function which is called from my setInterval function*" what is the end goal? You say "*I want to set a timout function [...] so it doesn't spam the window.open function*" but I find it hard to understand what you mean by that. If you want to prevent this *firing* too often, you can [debounce it](https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript) but I'm not sure if that's what you're after. – VLAZ Jul 20 '20 at 07:37
  • I want to pause the setinvertal for 30 secounds using setimout – Alpha Wolf Gamer Jul 20 '20 at 07:43

1 Answers1

1

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);
Ivar
  • 6,138
  • 12
  • 49
  • 61