Reputation: 1199
I am struggling to get a bit of code in jQuery to work... I want a function to fire, then loop after an initial set delay.
Code I am trying to go with is:
var delayTime = 1000;
setTimeout(function(){
function doLoop () {
var RandomID = Math.floor(Math.random() * 7) + 1
console.log("do loop")
var baubleSelected = ".bauble_0"+RandomID;
$(baubleSelected).toggleClass("bauble_fadeOut");
}
doLoop();
}, delayTime*9);
So, after initial 9000ms delay, call the function "doLoop". Work out a random integer and add that to a class name, then add the "bauble_fadeOut" class to that randomly selected element, that all works...
What is missing, is to get this "doLoop" function to happen again after a short delay - so we randomly then find another randomly selected element and toggle the "bauble_fadeOut" class on it .... repeating forever...
Any ideas?
Upvotes: 0
Views: 33
Reputation: 237975
First, you can simplify your call: you don't need the inner doLoop
function:
var delayTime = 1000;
setTimeout(function(){
var RandomID = Math.floor(Math.random() * 7) + 1
console.log("do loop")
var baubleSelected = ".bauble_0"+RandomID;
$(baubleSelected).toggleClass("bauble_fadeOut");
}, delayTime*9);
Now, it's simple to make this happen repeatedly. Either use setInterval
or put a call to setTimeout
at the end of the callback function:
var delayTime = 1000;
setInterval(function(){
var RandomID = Math.floor(Math.random() * 7) + 1
console.log("do loop")
var baubleSelected = ".bauble_0"+RandomID;
$(baubleSelected).toggleClass("bauble_fadeOut");
}, delayTime*9);
// OR
var delayTime = 1000;
setTimeout(function doLoop(){
var RandomID = Math.floor(Math.random() * 7) + 1
console.log("do loop")
var baubleSelected = ".bauble_0"+RandomID;
$(baubleSelected).toggleClass("bauble_fadeOut");
setTimeout(doLoop, delayTime*9);
}, delayTime*9);
Upvotes: 1