Search code examples
node.jsapiexpressqueuelimit

Limit function to only running once (even if called multiple times) per 5 minutes


I have a function within my Express/Node API that essentially does a 'roundup' of data after certain actions are performed.

Users can perform actions (call to an API route) multiple times in short intervals. After this API route is called, the roundup function is called. I don't want it called every time though; just once every 5 minutes for example (though still triggered by the API action).

I really only care about the final call (as roundup uses that info to update other data, but earlier ones are fine, as long as they are distanced apart (and not consecutive).

Basically what I want is: - even if the roundup function is called 20 times in, let's say 5 minutes, only run once

I've tried using lodash's debounce function for this; but it's still not working properly for me.

For example... (not real code, but base structure)

function roundup(){
// Do something here, but it's DB intensive and we really only care about the *final call* so only want it to run sometimes (?)

}

// API Route which will call roundup when finished
app.post('/list/join', (req, res) => {
   // my lodash attempt 
   let debounced_roundup = _.debounce(roundup, 300000);
   debounced_roundup();
});

I expect the debounce to hold up calling the roundup function until after the delay (300000), but because the API calls are individual, I don't think they are triggering the debounce as I expected.


Solution

  • You need to create the debouncer outside of your post method, or else you're creating a new, separate instance of the debouncer each time your API is called, which will know nothing of the previous triggerings.

    let debounced_roundup = _.debounce(roundup, 300000);
    
    // API Route which will call roundup when finished
    app.post('/list/join', (req, res) => {
       debounced_roundup();
    });