I'am currently working on a web app that shows the local time of a giving timezone, i am using a time zone api, i want a way to refresh the page or recall the api every second so i can update the seconds in my page.
I am working with node and express
I did some researchs and found some ways with socket.io but i am asking on some native node methos that can do the trick.
CodePudding user response:
One way to achieve this would be to use JavaScript to refresh the page every second by using the setInterval function.
setInterval(function() {
window.location.reload();
}, 1000);
CodePudding user response:
To refresh the page or call an API every second in a Node.js and Express application, you can use the setInterval
function from the JavaScript setInterval
function.
Here is an example of how you can use setInterval
to refresh the page every second:
app.get('/time', (req, res) => {
setInterval(() => {
// Send a request to the time zone API and render the response
request(timeZoneAPI, (error, response, body) => {
const data = JSON.parse(body);
res.render('time', { data });
});
}, 1000); // Refresh every 1000 milliseconds (1 second)
});
Keep in mind that setInterval
can be resource-intensive, as it runs a function repeatedly in the background. It's important to use it carefully and avoid using it for long periods of time or for tasks that are too resource-intensive.