Ofer Zelig
Ofer Zelig

Reputation: 17470

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?

Upvotes: 0

Views: 2439

Answers (3)

Raj Dave
Raj Dave

Reputation: 11

There is an awesome npm package available for this and many more other usecase:

https://vlio20.github.io/utils-decorators/

npm i utils-decorators

Just use the simple decorator:

import { debounce } from 'utils-decorators';

  class Example1 {

    @debounce(1000)
    foo(x: number): number {
      return 42;
    }
  }

Upvotes: 1

xdeepakv
xdeepakv

Reputation: 8125

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

Upvotes: 1

Yaroslav Gaponov
Yaroslav Gaponov

Reputation: 2099

Probebly you want debounced after send response like this code

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

global.i = 0;

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

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

Upvotes: 0

Related Questions