I am looking to iterate over a group of divs and perform some random actions at random times. I am attempting to use the following function but console.log
returns the same object and integer on every iteration. What would be the proper way to perform the following?
$('.cloud').each(function() {
$cloud = $(this);
ranNum = Math.floor(Math.random() * 5000);
setInterval(function() {
setTimeout("console.log($cloud + ranNum)", ranNum)
})
})
var
Because you're providing functionality as a string, you have to use global variables. Your code should be written with local variables defined within the event anonymous function closure like this:
$('.cloud').each(function() {
var $cloud = $(this);
var ranNum = Math.floor(Math.random() * 5000);
setInterval(function() {
// $cloud won't have any particular meaning though
console.log($cloud + ranNum);
}, ranNum);
});
setInterval
and setTimeout
Also I don't see a reason why you're using interval and timeout? Use one. Probably interval since you want something to repeatedly execute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With