Search code examples
node.jsdebouncing

Debounce to happen after a request has finished


I want to create a simple debounce function that would take place after a given Node.js request lifecycle has finished.

Let's have this simple Node/Express app:

const debounce = require('debounce')
const express = require('express')
const app = express()
const port = 4000

global.i = 0;

app.get('/test', (req, res) => {
    debounce(() => { global.i++; }, 3000, false);
    res.send(global.i.toString());
});

app.listen(port, () => console.log(`Listening on port ${port}`));

Whenever I call http://localhost:4000/ I get i as a response.

I would expect that as long as I call this endpoint under 3 seconds interval, the debounce function callback will not kick in, and i will be 0; and when I wait more than 3 seconds, it will run, and the next time I call the endpoint, I'd get an updated value (say 1).

But it doesn't happen. The response ends, and the code is "dead" - the debounce function callback is never triggered.

What's the right way to make things continue running in the background even after a request/response cycle has finished?


Solution

  • I am not sure. This is the right way or not. But you can create debounce using timestamp. See the example below

    const express = require("express");
    const app = express();
    const port = 4444;
    global.serverInfo = {
      lastUpdate: null,
      count: 0
    };
    
    app.get("/test", (req, res) => {
      updateValue();
      res.send(global.serverInfo.count.toString());
    });
    const updateValue = () => {
      if (global.serverInfo.lastUpdate) clearTimeout(global.serverInfo.lastUpdate);
      global.serverInfo.lastUpdate = setTimeout(() => {
        global.serverInfo.count = global.serverInfo.count + 1;
      }, 3000);
    };
    app.listen(port, () => console.log(`Listening on port ${port}`));