首页 > 解决方案 > 在 Node js 中创建计时器,每 10 分钟重置一次,并在点击 api 时返回当前分钟

问题描述

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

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

标签: javascriptnode.js

解决方案


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

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

推荐阅读