Saturday, 7 September 2013

Why does this code sometimes crash the browser?

Why does this code sometimes crash the browser?

Can anyone explain to me why this code sometimes enters an infinite loop
(presumably from the while loops) and crashes the browser window? Is it
something to do with while(userChoice != randNumber), does this not have a
sufficient end?
var check = function(userChoice) {
while ((isNaN(userChoice)) || (userChoice > 100) || (userChoice <
1) || (userChoice %1 !== 0)) {
userChoice = prompt("Choose a number between 1 - 100", "It must be
a whole number!");
}
};
var randNumber = Math.floor(Math.random() * 100 + 1);
var userChoice = prompt("Choose a number between 1 - 100");
console.log(userChoice);
check(userChoice);
//Above sorts out the computer choice and sets the rules for the user choice
while(userChoice != randNumber) {
if (userChoice > randNumber) {
userChoice = prompt("Your number is GREATER than the computer.",
"Please re-choose a number between 1 - 100");
check(userChoice);
}
else if (userChoice < randNumber) {
userChoice = prompt("Your number is SMALLER than the computer.",
"Please re-choose a number between 1 - 100");
check(userChoice);
}
}
console.log("Your number matches! Congratulations!");
This is a modification of some earlier code I had which would crash more
often. Although the above code is more stable, it still does crash
occasionally, although I am unable to explain the exact procedure to
initiate an infinte loop.
The old code is as follows: (as a priority can someone tells me why this
crashes? I don't see why the while loop doesn't end when the correct
number is reached!)
main = function() {
var randNumber = Math.floor(Math.random() * 100 + 1);
var userChoice = prompt("Choose a number between 1 - 100");
while ((isNaN(userChoice)) || (userChoice > 100) || (userChoice < 1) ||
(userChoice %1 !== 0)) {
userChoice = prompt("Choose a number between 1 - 100", "It must be a
whole number!");
}
//Above sorts out the computer choice and sets the rules for the user choice
while(userChoice !== randNumber) {
if (userChoice > randNumber) {
userChoice = prompt("Your number is GREATER than the computer.",
"Please re-choose a number between 1 - 100");
}
else if (userChoice < randNumber) {
userChoice = prompt("Your number is SMALLER than the computer.",
"Please re-choose a number between 1 - 100");
}
}
return("Your number matches! Congratulations!");
};
main();

No comments:

Post a Comment