I'm using setInterval()
inside a node.js express route with router.use()
, but after a short time, the interval starts to jump. It looks like it's been triggered more than once after some period. What can be wrong?
const router = express.Router();
router.use( (req, res, next) => {
// Wrong logging, starts to jump after some time
setInterval(update, 5000, "Updating inside router.use()...");
next();
});
function update(message) {
console.log(message, new Date())
}
// Correct logging (every 5 seconds)
setInterval(update, 5000, "Updating...");
This is the output:
Updating... 2022-02-24T21:50:41.545Z
Updating inside router.use()... 2022-02-24T21:50:46.025Z
Updating... 2022-02-24T21:50:46.545Z
Updating inside router.use()... 2022-02-24T21:50:51.026Z
Updating... 2022-02-24T21:50:51.546Z
Updating inside router.use()... 2022-02-24T21:50:56.027Z
Updating... 2022-02-24T21:50:56.547Z
Updating inside router.use()... 2022-02-24T21:50:58.155Z
Updating inside router.use()... 2022-02-24T21:51:01.028Z
Updating... 2022-02-24T21:51:01.548Z
Updating inside router.use()... 2022-02-24T21:51:03.156Z
Updating inside router.use()... 2022-02-24T21:51:06.028Z
Updating... 2022-02-24T21:51:06.549Z
Updating inside router.use()... 2022-02-24T21:51:08.156Z
Updating inside router.use()... 2022-02-24T21:51:10.339Z
Updating inside router.use()... 2022-02-24T21:51:11.030Z
I simplified my router.use() example overhere, but I need the setInterval() to work inside of it.
CodePudding user response:
Putting a setInterval()
inside of a router.use()
will start a new separate interval timer for every incoming request that hits this router. After two requests, you'll have two separate interval timers. After three requests, you'll have three separate interval timers and they will just continue to pile up forever - all running at the same time. So, the interval isn't jumping, you're just getting multiple interval timers overlapping and you're seeing the combined results of multiple timers running at once, each started at different times.
This cannot be the proper design.
Keep in mind that these timers run on behalf of the whole server, not just one user or one request. Once you start an interval timer, it keeps going forever until you call clearInterval(timerId)
on it.
You don't describe the actual design problem here (what problem you're trying to solve with the timers) so we can't really help with a suggested design. Most likely, you only want one timer, ever. Ideally, you wouldn't poll anything and would find a more event-driven design.