javascript - 在 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
推荐阅读
- php - 当我单击提交时,没有任何回声。为什么?
- sql - sql 加入时加入
- bash - 如何在 Jenkins 多行 shell 脚本中使用 bash 变量
- sql - 我们可以在oracle db的所有表中搜索一个字符串值吗
- c++ - C++ 观察者模式,“未命名类型”编译错误
- go - 函数中的动态返回类型
- vba - Worksheet.Protect 并不总是应用密码
- php - phpbench中的革命和迭代有什么区别?
- reactjs - React 和 forwardRef
- c# - 重定向到 DHL 跟踪站点时出现 IE 错误:属性 dcsMultiTrack 的值为 null 或未定义,不是函数对象