Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetInterval within jQuery .each()

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)
    })
})          
like image 457
jeffreynolte Avatar asked Dec 21 '22 15:12

jeffreynolte


1 Answers

Use local (closure) variables by using 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);
});

Unusual combination of 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.

like image 111
Robert Koritnik Avatar answered Jan 01 '23 16:01

Robert Koritnik