Reputation: 55
I want to create an API in Node js that return the time in minutes. When server start running, timer will also start. that timer will reset after every 10 minute. When I hit the API then the current time of timer should return. Like the current time in timer is 06:42 (6 minutes and 42 seconds) it will be response of API. when timer reach to 09:59 then it reset to 00:00
Please help me in this problem. Thanks.
Upvotes: 0
Views: 1100
Reputation: 30675
This script should do what you require, we record the time once we start the app, then reset every timer interval.
const port = 8080;
const app = express();
const timerDurationSeconds = 10 * 60;
let timerStart = new Date().getTime();
/* Reset the timer on each interval. */
setInterval(() => {
console.log("Resetting timer...");
timerStart = new Date().getTime();
}, timerDurationSeconds * 1000);
app.get('/timer', function(req, res) {
let elapsedSeconds = (new Date().getTime() - timerStart) / 1000;
let minutes = Math.floor(elapsedSeconds / 60 ).toFixed(0).padStart(2, "0");
let seconds = Math.round(elapsedSeconds % 60).toFixed(0).padStart(2, "0");
res.send( `${minutes}:${seconds}`);
})
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
Calling
curl http://localhost:8080/timer
should show the response.
This will look like (for example):
01:22
Upvotes: 3