Reputation: 10551
Be so kind as to take a look at this jsfiddle: http://jsfiddle.net/ne6sg/2/
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
setInterval(function(){
var interval = 500;
var paras = $('font');
var rand = Math.floor(Math.random() * paras.length);
paras.eq(rand).addClass('red');
},500);
});
</script>
<style>
.red {
color: red;
}
</style>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
Everything is working perfectly. When run, my script gives the class .red to page elements at random, using the setInterval function to give the class at a set rate. This rate is defined by the number on line7 of the script. When this number is made larger, the speed at which the class is added is slowed down, because of the larger interval.
However, I want that number on line7 to be an integer variable, and yet I can't get it to work.
IN CONCLUSION, why doesn't this work: http://jsfiddle.net/ne6sg/3/ ?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
setInterval(function(){
var interval = 500;
var paras = $('font');
var rand = Math.floor(Math.random() * paras.length);
paras.eq(rand).addClass('red');
},(interval));
});
</script>
<style>
.red {
color: red;
}
</style>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
<font color=#040404>Frabjous Day</font>
Thanks so much for your time.
Upvotes: 0
Views: 2852
Reputation: 12020
You are defining the interval
variable inside the function and trying to use it just outside.
Your js part would look something like the following:
$(document).ready(function() {
var interval = 500;
setInterval(function(){
var paras = $('font');
var rand = Math.floor(Math.random() * paras.length);
paras.eq(rand).addClass('red');
},1);
});
See this: http://jsfiddle.net/ne6sg/6/
Upvotes: 0
Reputation: 100371
Define interval
out of the scope of the setInterval
var interval = 500; // this line, declare it here
setInterval(function(){
var paras = $('font');
var rand = Math.floor(Math.random() * paras.length);
paras.eq(rand).addClass('red');
}, interval); // so it exists in this context
Upvotes: 2