Milan
Milan

Reputation: 97

JavaScript code execution delay

function append(what) {
    $("#drawer").append(what);
}

function outerHtml(o) {
    return $("<div />").append($(o).clone()).html();
}

var allPixel = [];

$(".pix").each(function() {
    allPixel.push(outerHtml($(this)));
});

$("#drawer").empty();

var index;

for (index = 0; index < allPixel.length; index++) {
    pixel = allPixel[index];
    setTimeout(append(pixel), 100);
}

I have a Container (#drawer) that is full of many div elements. In this function the HTML of each of these div elements gets saved in an array individually. When its done doing that the div element gets cleared.

In the Array allPixel are now all div elements. I want it so that each div element gets added to #drawer with a delay of 100ms.

Problem:

If I run this function nothing happens (the divs are not disappearing/ appearing). What did I do wrong?

If anything is unclear feel free to let me know and I will edit my question.

Question aswered... See it in action: https://wiese2.lima-city.de/test/

Upvotes: 0

Views: 51

Answers (1)

Satpal
Satpal

Reputation: 133403

You are invoking the method invoking immediately and passing its return value i.e. undefined to setTimeout.

You can set additional parameters to be passed to append function when timer expires to setTimeout method.

Use

setTimeout(append, 100 * (i + 1), pixel);

Additionally you also need to increase timer based on element index

Upvotes: 2

Related Questions