我的变量normalWeek
等于一个特定的时间段,如果这个时间段为真,那么第一个条件将被执行,如果它不是,while循环将执行第二个条件,直到变量normalWeek
为真。但问题是,当我执行代码时,循环发现的第一个条件为真将是唯一执行的条件,即使在另一个条件为真之后。
例如,如果是早上6点,变量normalWeek
为真,但是即使不是早上6点,循环也会继续执行相同的条件,它基本上忽略了另一个条件。
var date = new Date();
var hour = date.getHours();
var day = date.getDay();
var minute = date.getMinutes();
function goodSignal() {
console.log(b, 'Good Signal');
}
function badSignal() {
console.log(b, 'Bad Signal');
}
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
let b = 0;
let normalWeek = (hour === 6 || hour === 10) && (day > 0 && day < 6);
while (b === 0) {
console.log('Testing Started...');
while (normalWeek === true) {
b++;
goodSignal();
sleep(10000);
continue;
}
while (normalWeek === false) {
b++;
badSignal();
sleep(10000);
continue;
}
}
嗨Iago:看看下面的代码:我在注释中包含了解释。它说明了如何检查"正常的一周"。每次使用一个新的日期,而不是重复使用相同的日期。我已经尽力解释了你问题的目的,但如果你想澄清什么,请在评论中告诉我,我会检查的。
// This will compute a new date every time instead of using the same date each time
function isNormalWeek () {
const date = new Date();
const day = date.getDay();
const hours = date.getHours();
// return (hours === 6 || hours === 10) && (day > 0 && day < 6);
// Just for this example, let's say it's normal if the seconds are even
// instead of waiting for 06:00-06:59 or 10:00-10:59 on a weekday
const seconds = date.getSeconds();
return seconds % 2 === 0; // seconds are even
}
// This is preferable to running a loop endlessly for no reason
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main () {
function goodSignal () {
console.log(b, 'Good Signal');
}
function badSignal () {
console.log(b, 'Bad Signal');
}
let b = 0;
// Always true, loop forever
while (true) {
b += 1;
// Invoke one function if the week is "normal", otherwise invoke the other
isNormalWeek()
? goodSignal()
: badSignal();
// await sleep(10_000);
// Just for this example, let's run the loop again after waiting one second
// instead of waiting ten seconds
await sleep(1_000);
}
}
main();