user1584421
user1584421

Reputation: 3863

Send content at intervals in JavaScript/Node.js

I want to execute a particular line of code at timed intervals. The line will be res.write(""), to keep a connection alive.

This is similar to hardware interrupts in embedded systems.

Is it possible to have a function that inside will run my code, but at 20 seconds period to execute one particular line of code?

Upvotes: 1

Views: 783

Answers (2)

Ivan Velichko
Ivan Velichko

Reputation: 6709

The code res.write("") not necessary will send something to the wire, since the payload is empty. What you might need is TCP keepalive functionality.

 res.connection.setKeepAlive(true, 20000)

Upvotes: 4

Joel Lord
Joel Lord

Reputation: 2173

You can use setInterval

https://developer.mozilla.org/fr/docs/Web/API/WindowTimers/setInterval

setInterval(() => res.write(""), 20000);

Upvotes: 2

Related Questions