Search code examples
javascriptasynchronouspromisepolling

JS : Set a time so that the progress bar is not displayed if the data is read again within a certain number of seconds


// read data with progress
function nprogressWrapPromise(fn, hide = false) {
    if(hide) {
        // no progress
        return fn()
    }
    // have progress
    const done = nprogressStartLoad();
    return fn().then(() => {
      done();
    });
}

function print(message) {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log(message);
            resolve();
        }, 1000);
    });
}

call nprogressWrapPromise multiple times in different places

nprogressWrapPromise(async () => {
    return await print("one")
}) 
nprogressWrapPromise(async () => {
    return await print("two")
}) 
nprogressWrapPromise(async () => {
    return await print("three")
}) 

I use the NProgress to when I ask the promise ,the page is display the propress


let started = 0;

 function nprogressStartLoad() {
  if (started == 0) {
    window.NProgress.start()
  }
  started++;
  return () => {
    started--;
    if (started <= 0) {
      started = 0;
      window.NProgress.done();
    }
  }
}

I want to add the time, in the five seconds, only the first promise have process, the others promise dont have process.


Solution

  • You can do it like this:

    let promise = undefined;
    function print(message) {
        if (promise) return promise;
        return promise = new Promise(function (resolve, reject) {
            setTimeout(function () {
                console.log(message);
                resolve();
                promise = undefined;
            }, 1000);
        });
    }
    

    So, we use promise as a semaphor. Whenever a new promise is created, we simply store it into the variable called promise and we will proceed reusing this variable instead of creating a promise for references even while the promise is not resolved yet. Once the promise is resolved, we set promise to undefined, so at the next call of print we will have a new Promise.

    EDIT

    Similarly to the semaphore above, you can use another semaphore for your other function:

    let npprogressWrapPromiseDone = undefined;
    // read data with progress
    function nprogressWrapPromise(fn, hide = false) {
        if(hide) {
            // no progress
            return fn()
        }
        if (npprogressWrapPromiseDone) return npprogressWrapPromiseDone;
        // have progress
        const done = nprogressStartLoad();
        return npprogressWrapPromiseDone = fn().then(() => {
          done();
        });
    }