Home > Net >  Force reset promise when re-activated
Force reset promise when re-activated

Time:12-04

I'm attempting to have an async function that resets if it's recalled. This function is linked to multiple buttons, and triggers a div acting as a notification overlay box.

I would like, when the callAlert() function is called again, it resets the timeout on clearAlert(). I attempted to add 1500 ms when the newAlert is called, but I'm assuming that when any of the buttons (which trigger callAlert()) is clicked, it's already moved onto the clearAlert() promise. Either that, or I end up with a longer and longer wait time as it accumulates.

Any advise would be great.

let alertActive = false;
let alertCd = 0;

function newAlert(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            alert_pop.classList.remove("alert_pop");
            alertActive=true;
            alertCd = 1500
            resolve();
        } , 100);
    });
}

function clearAlert(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            alert_pop.classList.add("alert_pop");
            alert_string.innerHTML="";
            resolve();
         } , alertCd);
         alertActive=false;
    });
}

async function callAlert(){
        await newAlert();
        await clearAlert();
}

CodePudding user response:

Creating a resetable timer

If you want to create a timer that can be reset,

  1. Save the timeoutID returned by setTimeout().
  2. Any time a new alert needs to be created, cancel the last timer using clearTimeout(), then create a new timeout.

Cancelling the timer

If you need to cancel an existing timer, use clearTimeout(). Right now, clearAlert() creates its own Promise and tries to set its own timeout. You should change clearAlert() not to return a Promise (at least, for now. It looks like you may be trying to delay the cancellation).

First, in newAlert(), save resolve or reject from the active Promise to a scope that is accessible by clearAlert(). Then, in clearAlert(), call clearTimeout() and resolve() or reject() (depending on what you're trying to do).

CodePudding user response:

To ensure that a JavaScript function is not called more than once every few seconds, you can run wrap it in the “debounce” function available in lodash.

here is a well explained example.

  • Related