I want to create a server, when a GET is requested for which the date and time will be displayed in the server console. And after a certain interval, complete the server response and return the time to the client.
I do it this way.
const http = require('http'); const port = 3000; const getDateToUTC = () => (new Date).toUTCString(); const server = http.createServer((req, res) => { if (req.method === 'GET') { const interval = setInterval(() => console.log(getDateToUTC()), 1000); setTimeout(() => { clearInterval(interval); res.end(getDateToUTC()); }, 5000) } }); server.listen(port, () => { console.log(`Server running on port: ${port}`); }); But! When a server is repeatedly accessed, the function will only work when all previous answers have been given.
Those. I open two tabs in the browser and switch to localhost:3000 . I try to quickly go, well, probably, there will be a difference of 500 ms between requests. And I expect to receive answers from the server at the same interval.
In fact, the second request begins to be processed only after the first one is completed, i.e. after 5 seconds in this example.
How to make requests work asynchronously?
