Nim
Nim

Reputation: 55

javascript asynchonously update a div

I need to show multiple images in a DIV in a web page one after another. There should be a time gap between two images. Here is the code I tried for that.

$('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/cat2.png" />')
    wait(1000);
    $('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/dog1.png" />')
    wait(1000);
    $('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/dog2.png" />')
    wait(1000);
    $('#abc').prepend('<img id="theImg" src="D:/Image_Store/Character/Animal/Pet/parrot1.png" />')
    wait(1000);

EDIT

wait function is here

function wait(ms){
       var start = new Date().getTime();
       var end = start;
       while(end < start + ms) {
         end = new Date().getTime();
      }
    }

But this is not working and only show the last image. How can I figure out that?

Upvotes: 3

Views: 35

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075209

You can't suspend execution of JavaScript code between lines in a browser. (Not in a useful way; alert and such sort of do.) Or at least, if you do, the entire UI of the browser (or at least that tab) locks up and no page updates are rendered.

Instead, schedule a series of timed callbacks to update your image:

[   "D:/Image_Store/Character/Animal/Pet/cat2.png",
    "D:/Image_Store/Character/Animal/Pet/dog1.png",
    "D:/Image_Store/Character/Animal/Pet/dog2.png",
    "D:/Image_Store/Character/Animal/Pet/parrot1.png"
].forEach(function(img, index) {
    setTimeout(function() {
        $("<img>").attr("src", img).prependTo("#abc");
    }, 1000 * index);
});

There we schedule the first update after 0ms, the second after 1000ms, the third after 2000ms, etc.


Side note: Your original code was adding multiple img elements with the same id value. The code above still uses multiple img elements, but doesn't give them an id, since using the same id on more than one element is invalid.

If your goal was to have a single img element that you updated with multiple sources, we'd do that slightly differently:

[   "D:/Image_Store/Character/Animal/Pet/cat2.png",
    "D:/Image_Store/Character/Animal/Pet/dog1.png",
    "D:/Image_Store/Character/Animal/Pet/dog2.png",
    "D:/Image_Store/Character/Animal/Pet/parrot1.png"
].forEach(function(img, index) {
    if (index === 0) {
        // Create and append the img
        $("<img>").attr("id", "theImg").attr("src", img).prependTo("#abc");
    } else {
        // Update it
        setTimeout(function() {
            $("#theImg").attr("src", img);
        }, 1000 * index);
    }
});

Upvotes: 5

Related Questions