asynchronousscopesettimeoutsveltecleartimeout

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);
        }
    };

Solution

  • Define the timeout in the module scope:

    let splashTimeout;
    
    function splashHandler() {
      clearTimeout(splashTimeout);
    
      showSplash = true;
    
      splashTimeout = setTimeout(() => {
        showSplash = false;
      }, 2000);
    }