Reputation: 16501
I'm trying to create a random quote generator. I have created a function called timer that runs another function pickQuote every 400ms but at the moment this doesn't seem to work. in pickQuote I run a function randomNumberGen that creates a random number. My problem in the randomNumberGen is that I want to have an if or if..else in place that checks whether or not the new random number is different from the current quotes[randomNumber] but i'm unsure how to do this.
Can anyone provide me with some insight on how I can achieve this?
My current effort can be viewed here: http://jsbin.com/aqinud/12/edit
Upvotes: 0
Views: 534
Reputation: 5231
Perhaps something like this:
var currentNumber = -1;
function randomNumberGen() {
var num = parseInt(Math.random() * (len) );
if(currentNumber != num){
currentNumber = num;
return num;
} else {
return randomNumberGen();
}
}
I noticed you had incorrectly passed 'pickQuote' to setInterval. Try wrapping the callback in an anonymous function:
function timer() {
runQuotePicker = setInterval(function(){
pickQuote();
}, 1000);
}
Otherwise you're scheduling the result of pickQuote to be invoked ever x milliseconds.
Upvotes: 3
Reputation: 154908
index
is not defined outside $.each
. Variables in functions are not accessible outside it if you use var
.
What I recommend is altering the function as follows:
function randomNumberGen() {
//generate randomNumber based on length of array
// round it down (parseInt is for string->number conversion)
var thisRandomNumber = Math.floor(Math.random() * len);
if ( randomNumber === thisRandomNumber ) {
randomNumberGen();
} else {
randomNumber = thisRandomNumber;
}
}
So, first create a random number and only if it's different from randomNumber
, update it with the newly created one. Otherwise, try again.
Also, setTimeout
requires a function, so don't invoke it yet:
runQuotePicker = setInterval(pickQuote, 400);
http://jsbin.com/aqinud/13/edit
Upvotes: 3