在 Node js 中创建计时器,每 10 分钟重置一次,并在点击 API 时返回当前分钟数



我想在 Node js 中创建一个 API,以分钟为单位返回时间。 当服务器开始运行时,计时器也将启动。该计时器将在每 10 分钟重置一次。 当我点击 API 时,计时器的当前时间应该返回。 就像计时器中的当前时间为06:42(6 分 42 秒(一样,它将是 API 的响应。 当计时器达到09:59时,它会重置为 00:00

请帮助我解决这个问题。 谢谢。

此脚本应该执行您的要求,我们在启动应用程序后记录时间,然后重置每个计时器间隔。

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}`);

curl http://localhost:8080/timer 

应显示响应。

这将看起来像(例如(:

01:22

最新更新