user198989
user198989

Reputation: 4665

Sleep 1 second and then append?

I need to add iframes with waiting 1 second between adding each other, instead of adding all at once. Tried this with no luck, it just append it all at once.

var  i = 0;

function appendSomeItems() {
  for (var j=0; j<50; i++, j++) {
    $('body').append('<iframe src="http://www.example.com"></iframe>').delay(1000);
  }
  if (i < 50) window.setTimeout(appendSomeItems, 0);
}

appendSomeItems();

What is the correct way to do that ? thanks.

Upvotes: 0

Views: 120

Answers (3)

Cheery
Cheery

Reputation: 16214

for (var j = 0; j < 50; j++) {
  setTimeout(function() {
     $('body').append('<iframe src="http://www.example.com"></iframe>');
  }, j * 1000);  // each call is scheduled to run after j seconds
}

ps: do not use very large numbers or use setInterval with single function, counter and cleanup of the timer after the required number of calls was established or setTimeout the next call at the end of the current call of the timed function. Just skip that step at the last call.

Upvotes: 7

BrunoLM
BrunoLM

Reputation: 100361

jQuery's delay method is used for animations.

What you need to do is trigger the method every second. In order to do that you could write:

var itemsToAppend = 50;

function appendSomeItems()
{
    $('body').append('<iframe src="http://www.example.com"></iframe>');

    if (itemsToAppend--) // if 0 skips
        setTimeout(appendSomeItems, 1000);
}

appendSomeItems();

Upvotes: 0

orhanhenrik
orhanhenrik

Reputation: 1415

Another option is to use the following code, which adds a new timeout after the previous one is finished. So you will never have multiple timeouts waiting.

var start=0;
var max=50;
function appendSomeItems(i) {
    $('body').append('<iframe src="http://www.example.com"></iframe>');
    if(i<max){
        setTimeout(function(){appendSomeItems(i+1)},1000);
    }
}
appendSomeItems(start);

Upvotes: 1

Related Questions