I am trying to use a Firebase array value (array1) in my checkAndPush function but the console says the array is undefined when called outside of the firebaseArrayValFunction. Any ideas on how to solve this or why it is happening?
Thank you for taking a look.
$( document ).ready(function() { console.log( "ready!" );
var myFirebaseRef = new Firebase("https://firebaseio.com/");
myFirebaseRef.set({
quote: [" Quote 1","Quote 2","Quote 3"]
});
var array2 = [];
var array1 = [];
var array1Random;
var array2Random;
var firebaseArrayValFunction = myFirebaseRef.child("quote").on("value", function(snapshot) {
var array1 = snapshot.val();
var array1Random = array1[Math.floor(Math.random()*array1.length)];
console.log(array1);
console.log(array1Random);
});
var restart = setTimeout(checkAndPush, 1000);
function checkAndPush() {
//This if statement should say array.length === 0 but that will run infinitely at the moment because array1.length is undefined so 6 is there to keep //the function from immediately calling checkAndPush2
if (array1.length === 6) {
console.log("ARRAYS ARE EQUAL");
checkAndPush2();
return false;
}else if(jQuery.inArray(array1Random, array2) !== -1){
console.log("its there");
setTimeout(checkAndPush, 5000);
} else {
array2.push(array1Random);
var index = array1.indexOf(array1Random);
array1.splice(index,1);
console.log(array1);
console.log(array2);
setTimeout(checkAndPush, 5000);
}
}
function checkAndPush2() {
var array2Random = array2[Math.floor(Math.random()*array2.length)];
if (array2.length === 0) {
console.log("ARRAYS ARE EQUAL");
checkAndPush();
return false;
}
else if(jQuery.inArray(array2Random, array1) !== -1){
console.log("its there");
setTimeout(checkAndPush2, 5000);
}
else{
array1.push(array2Random);
var index = array2.indexOf(array2Random);
array2.splice(index,1);
console.log(array1);
console.log(array2);
setTimeout(checkAndPush2, 5000);
}
}
});