使用 setTimeout 创建一个循环,直到一分钟,然后每五分钟
Creating a loop using setTimeout up to the minute, then every five minutes
我想查看分钟,直到我到达 :00、:05、:10 等分钟,然后设置为 5 分钟(分钟)并在申请期间继续。有一个更好的方法吗?我需要一个 clearTimeout 吗?请帮助并感谢!
目标:查看分钟,00、05、10、15、30 等一次更改为 5 分钟间隔并保持 运行。
// Set to 1 minute initially.
let interval = 60000;
function timeCheck() {
const date = getNow();
console.log("checking...", `${dayjs(date).hour()}:${dayjs(date).minute()}:${dayjs(date).second()}`);
// Check browser time in minutes for 00, 05, 10, 15, 20, etc.
if (dayjs(date).minute() % 5 === 0) {
// Set to 5 minute.
interval = 300000;
...
}
setTimeout(timeCheck, interval);
}
clearTimeout(timeCheck);
timeCheck();
console.log("Starting...");
const task = () => {
console.log("do something");
}
let minuteInterval;
const checkMinuteInterval = () => {
const date = new Date();
if (date.getMinutes() % 5 === 0) {
clearInterval(minuteInterval);
task();
setInterval(task, 1000 * 60 * 5);
} else {
console.log("Not on multiple of 5");
}
};
minuteInterval = setInterval(checkMinuteInterval, 1000 * 60);
checkMinuteInterval();
一种完全不同的方法,因为这看起来像 an XY problem, is to just have an interval for every minute, check if it's a multiple of 5, if so do something, otherwise just break out of the function. (As suggested by @Heretic Monkey)
console.log("Starting...");
const task = () => {
if ((new Date()).getMinutes % 5 !== 0) {
console.log("Not a multiple of 5 minutes");
return; // would just be return; in production code
}
console.log("Do something")
// rest of function...
}
task();
setInterval(task, 1000 * 60);
我想查看分钟,直到我到达 :00、:05、:10 等分钟,然后设置为 5 分钟(分钟)并在申请期间继续。有一个更好的方法吗?我需要一个 clearTimeout 吗?请帮助并感谢!
目标:查看分钟,00、05、10、15、30 等一次更改为 5 分钟间隔并保持 运行。
// Set to 1 minute initially.
let interval = 60000;
function timeCheck() {
const date = getNow();
console.log("checking...", `${dayjs(date).hour()}:${dayjs(date).minute()}:${dayjs(date).second()}`);
// Check browser time in minutes for 00, 05, 10, 15, 20, etc.
if (dayjs(date).minute() % 5 === 0) {
// Set to 5 minute.
interval = 300000;
...
}
setTimeout(timeCheck, interval);
}
clearTimeout(timeCheck);
timeCheck();
console.log("Starting...");
const task = () => {
console.log("do something");
}
let minuteInterval;
const checkMinuteInterval = () => {
const date = new Date();
if (date.getMinutes() % 5 === 0) {
clearInterval(minuteInterval);
task();
setInterval(task, 1000 * 60 * 5);
} else {
console.log("Not on multiple of 5");
}
};
minuteInterval = setInterval(checkMinuteInterval, 1000 * 60);
checkMinuteInterval();
一种完全不同的方法,因为这看起来像 an XY problem, is to just have an interval for every minute, check if it's a multiple of 5, if so do something, otherwise just break out of the function. (As suggested by @Heretic Monkey)
console.log("Starting...");
const task = () => {
if ((new Date()).getMinutes % 5 !== 0) {
console.log("Not a multiple of 5 minutes");
return; // would just be return; in production code
}
console.log("Do something")
// rest of function...
}
task();
setInterval(task, 1000 * 60);