My variable normalWeek is equal to a certain time period, if this time period is true then the first condition will be executed if it is not the while loop will execute the second condition until the variable normalWeek becomes true. But the problem is that when I execute the code the first condition that the loop finds to be true will be the only one executed even after another condition becomes true.
For example, variable normalWeek is true if it is 6 am, but the loop will continue to execute this same condition even after it is not 6 am, it basically ignores the other condition.
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;
}
}
Hi Iago: Take a look at the code below: I included explanations in comments. It illustrates how you can check for a "normal week" using a new date each time instead of reusing the same date. I did my best to interpret your question's objective, but if you want to clarify something, just let me know in a comment and I'll check it out.
// 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();