1

I have a main function with a setTimeout function inside of it that uses a random interval each time the main function is called. Once the timeout triggers it will run the main function again and create a new timeout. However I can manually run the main function multiple times, continuously generating additional randomly timed setTimeouts. I don't want this to happen, I need the timeouts to overwrite each other each time they are made so that only one can exist at a time. I have applied a couple of fixes already which seem to work in theory but in practice fail. Here is my code:

mainFunc {
    var timeout;
    console.log(timeout)
    clearTimeout(timeout);
    timeout = setTimeout(mainFunc(), randomTime)
}

As you can see clearing the timeouts and restating the variable both fail to change the behavior of the program. Any ideas are greatly appreciated.

Aurel
  • 31
  • 6
  • 1
    You need to (1) correct the `mainFunc` syntax (functions require a parameter list) (2) declare `timeout` outside so it's persistent (3) pass `mainFunc` to `setTimeout` instead of calling it immediately – CertainPerformance Dec 24 '20 at 01:44
  • You are creating a local variable of timeout. Consider your scoping here! –  Dec 24 '20 at 01:44
  • @CertainPerformance Thank you very much, I have corrected the scope of the timeout variable and this has fixed the problem. I'm still kinda confused however, I thought that calling the timeout variable over again would simply overwrite it? – Aurel Dec 24 '20 at 01:52
  • Not if you just created a *different binding* – CertainPerformance Dec 24 '20 at 01:53

0 Answers0