开发者

SetInterval within jQuery .each()

开发者 https://www.devze.com 2023-02-26 20:10 出处:网络
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

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 prop开发者_运维问答er way to perform the following?

    $('.cloud').each(function() {
    $cloud = $(this);
    ranNum = Math.floor(Math.random() * 5000);
    setInterval(function() {
        setTimeout("console.log($cloud + ranNum)", ranNum)
    })
})          


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.


Please.. never use a string as the first setInterval/setTimeout argument

$('.cloud').each(function () {
    var $cloud = $(this);
    var ranNum = Math.floor(Math.random() * 5000);
    setTimeout(function () {
        console.log($cloud, ranNum);
    }, ranNum);
});


There are a few things wrong with your function so I'm going to rewrite and explain after:

$('.cloud').each(function(i,d) {
    var cloud = $(this);
    var randNum = Math.floor(Math.random() * 5000);

    setTimeout(function(){
        console.log(cloud + ranNum)
    }, randNum );
});

I don't understand why you are trying to output cloud variable because this will just display HTMLElement or similar. Also, you are trying to put a timer inside a interval, both are the same, but the interval will keep looping, the timer will output once.

If you are trying to output which number cloud you are referencing. Use i instead of cloud.

Try define your variables a little cleaner, this is not PHP, refrain from using $ and don't forget var for initial definitions and ; to end statements!

Hope this helped.


There are good answers here. I will add that because you did not declare ranNum it ends up being a global variable and every iteration of the loop will overwrite the previous value instead of creating a new variable. Thus the number you see in the log output will always be whatever random value was produced during the last iteration of the loop.

So, always declare your variables!

0

精彩评论

暂无评论...
验证码 换一张
取 消