[英]Javascript while loop infinite loop
I'm not all that experienced of a code and I'm stuck on a the while loop towards the bottom of the block of code below 我不是所有的代码经验者,我被困在while循环中,朝向下面的代码块底部
My code is supposed to get the date, check if today is a day when we don't ship (saturdays, sundays, holidays) and, if it is, add 1 day until until it finds the next day that we are on open on and write it to the document. 我的代码应该获取日期,检查今天是否是我们不发货的日期(星期六,星期天,节假日),如果是,则增加1天,直到找到第二天我们开始营业为止并将其写入文档。
var target = new Date();
var targetDay = target.getDay();
var targetDate = target.getDate();
var targetMonth = target.getMonth();
function checkIfClosedOnTarget(targetDay,targetDate,targetMonth){
var areOpenOnTarget = true;
if(
targetDay == 0 ||
targetDay == 6 ||
(targetDate == 1 && targetMonth == 0) || // New Year's Day
(targetMonth == 4 && targetDate >= 25 && targetDay == 1) || // Memorial Day
(targetMonth == 6 && targetDate == 4) || //Independence Day
(targetMonth == 8 && targetDate <= 7 && targetDay == 1)|| //Labor Day
(targetMonth == 10 && targetDate <= 28 && targetDate >= 22 && targetDay == 4)|| // Thanksgiving Day
(targetMonth == 11 && targetDate == 25)
){
areOpenOnTarget = false;
}
if(areOpenOnTarget){
return true;
}else{
return false;
}
};
function addDaysUntilNextOpenDay() {
while(checkIfClosedOnTarget(targetDay,targetDate,targetMonth) == false){
target.setDate(target.getDate() + 1);
}
};
addDaysUntilNextOpenDay();
document.write("<p>Next shipment will ship out on " + target.getMonth() + " " + target.getDate + ", " + target.getYear) + " at 4:00pm Pacific Standard Time ";
The problem is with this line target.setDate(target.getDate() + 1);
问题是这一行
target.setDate(target.getDate() + 1);
you update the target
but you never update the targetDay
, targetDate
, targetMonth
variables... so the checkIfClosedOnTarget()
function keeps getting passed the same values, resulting in the infinite loop . 您更新了
target
但从未更新targetDay
, targetDate
, targetMonth
变量...,因此checkIfClosedOnTarget()
函数不断传递相同的值,从而导致无限循环 。
So you might want to update them after you set the next day: 因此,您可能需要在设置第二天后进行更新:
while(checkIfClosedOnTarget(targetDay,targetDate,targetMonth) === false){
target.setDate(target.getDate() + 1);
// update parameters
targetDay = target.getDay();
targetDate = target.getDate();
targetMonth = target.getMonth();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.