user3099199
user3099199

Reputation: 49

Add loop to setTimeout

JS:

setTimeout(function() {
    $('#houses div:last').after('<div class="item current-last '+ randClass +'"></div>');

}, 2000);

But once a time. I want a loop. How can I fix it?

var house = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
randClass = house[Math.floor(Math.random() * house.length)];

Upvotes: 0

Views: 64

Answers (4)

dana
dana

Reputation: 18105

Use setInterval instead of setTimeout. The former sets a timer that is called on an interval, whereas the later sets a timer that is called only once.

Also, call the randomization code every time you modify the DOM. An easy way to do this is to include it in the interval function as follows:

setInterval(function() {
    var house = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
    var randClass = house[Math.floor(Math.random() * house.length)];

    $('#houses div:last').after('<div class="item current-last '+ randClass +'"></div>');
}, 2000);

Upvotes: 3

Ringo
Ringo

Reputation: 3965

Try this:

var intv = setInterval(test, 2000);
// you can also clear the interval 
// by use clearInterval(intv);
function test(){
   $('#houses div:last').after('<div class="item current-last '+ randClass +'"></div>');
}

Upvotes: 0

nestedloop
nestedloop

Reputation: 2646

You need to use:

setInterval(//insert your function and interval here)

That will solve the 'execute only once' issue.

As for wanting to get different randClass values, you need to manage that, do something that modifies the value of randClass, between intervals, to suit you purpose. As @Lanello proposed, you could randomize it. Or maybe increment it. Whatever your application logic dictates.

Upvotes: 2

Lanello
Lanello

Reputation: 59

you simply must write a

function RandomizeClass()

and call it inside the SetTimeout, instead of write it inside, surely you set the randClass value before the setTimeout and then its value never change.

Upvotes: 0

Related Questions