Im building a small random sequence comparitor in order to learn js objects, at the moment I’m having a problem where if I increment the limit variable within my completeMessage() this gets automatically run within the the for loop of my compareSequences() resulting in an infinite loop, could anyone advise me where I may being going wrong?
2 methods in question:
compareSequences: function() {
var instance = this;
var i = 0;
for( i; i <= limit; i++ ) {
console.log('Limit inside loop:', limit);
if( stacks.randomSequence[i] != stacks.userSequence[i] ) {
instance.errorMessage();
return;
}
if( i === limit ) {
instance.completeMessage();
}
console.log('Limit now', limit);
}
},
completeMessage: function() {
var instance = this;
alert('Well done you where right!');
limit = 5; //currently set as test, changing to ++ results in infinite loop
instance.selectors.startButton.removeAttr('disabled');
overallScore++;
instance.selectors.scoreCounter.html(overallScore);
},
Link to my fiddle: http://jsfiddle.net/FNd79/22/
Your
limitvariable is by default defined on the global scope (as a property of the objectwindow) changing it’s value in one function changes it everywhere.Be sure to define it as a local of your class using
var.Your issue is that you modify your upper bound during the loop, in a way that it increases of one every time you are going to exit the loop.
You need the global value at the time you init the loop, you can just copy it to a local variable at that time:
You could alternatly use the keyword
breakto exit the loop for sure.