lache
lache

Reputation: 830

clearTimout reference before initialization

I need to clear this timeout before running the next. But how do i do that with the scope issue?

function splashHandler() {
  clearTimeout(splashTimeout); // <--can't call before initialization...

  showSplash = true;

  let splashTimeout: NodeJS.Timeout = setTimeout(() => {
    showSplash = false;
  }, 2000);
}

UPDATED - used answer from below

//create a timeout variable...has to define it?
    let splashTimeout = setTimeout(() => {
        console.log('set');
    }, 2000);

    //Clear and set the timeout...
    const splashTimeoutHandler = () => {
        showSplash = true;
        if (splashTimeout) {
            clearTimeout(splashTimeout);
            splashTimeout = setTimeout(() => {
                showSplash = false;
            }, 2000);
        }
    };

Upvotes: 1

Views: 75

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206595

Define the timeout in the module scope:

let splashTimeout;

function splashHandler() {
  clearTimeout(splashTimeout);

  showSplash = true;

  splashTimeout = setTimeout(() => {
    showSplash = false;
  }, 2000);
}

Upvotes: 2

Related Questions