I noticed some people here recommend to use await/async and promise instead of setTimeout directly when you want to delay the execution of something. This is the code:
async wait (ms){
return new Promise(resolve => setTimeout(resolve, ms));
}
So I would use
await wait(3000);
my_function();
instead of
setTimeout(() => {
my_function();
}, 3000);
It makes sense but I noticed that if I do that I get increased memory usage and eventually the app crashes with heap of out memory after a few hours.
Is this an issue in the promise design of nodejs, or am I missing something here?
This code reproduces the issue:
const heapdump = require('heapdump'),
fs = require('fs');
class test {
constructor(){
this.repeatFunc();
}
async wait (ms){
return new Promise(resolve => setTimeout(resolve, ms));
}
async repeatFunc(){
// do some work...
heapdump.writeSnapshot(__dirname + '/' + Date.now() + '.heapsnapshot');
await this.wait(5000);
await this.repeatFunc();
}
}
new test();
Notice heap dump keeps increasing every 5 seconds
With setInterval this doesn't happen:
const heapdump = require('heapdump'),
fs = require('fs');
class test {
constructor() {
setInterval(this.repeatFunc, 5000);
}
repeatFunc() {
// do some work...
heapdump.writeSnapshot(__dirname + '/' + Date.now() + '.heapsnapshot');
}
}
new test();