Why does everything display at once, using setTimeout in Javascript?

I'm trying to make a few things scroll down the screen in javascript, however, upon execution, it just says a little and displays everything at once. So it's not clearing with the $("#Menu").html('') function and the setTimeout(function {},500) is just setting a timeout for the entire page instead of the code segment.

var MenuData = [
{'Name':'pictures','x':'30'},
{'Name':'blog','x':'50'},
{'Name':'contact','x':'42'}
]
;  


var PositionArray = new Array();
$(document).ready(function () {
    for (var count = 0; count < 1000; count++) {
        $("#Menu").html('');
        if (PositionArray[count] != null) {
            PositionArray[count]++;
        } else {
            PositionArray[count] = 0;
        }

        setTimeout(function () {
        for (var i in MenuData) {
                $("#Menu").append('<div style="position:relative; left:' + MenuData[i].x + 'px; top:' + PositionArray[i] + 'px; ">123</div>');
            }
        }, 500);

    }
});

Here's the fiddle: http://jsfiddle.net/LbjUP/

Edit: There was a little bit of error in the code that doesn't apply to the question. Here's the new one: http://jsfiddle.net/LbjUP/1/, I just moved PositionArray[count] to the setTimeout function as PositionArray[i]

Answers:

Answer

As stated in the comments, you are creating 1000 timeouts for 500 ms at the same time - after 500 ms all of them will be executed. What you want is to increase the timeout for every scheduled function:

setTimeout(function() {
    // do something
}, count * 500);

However, creating 1000 timeouts at once is not a that good idea. It would be better to use setInterval or call setTimeout "recursively" until a count of 1000 is reached, so that you only have one active timeout at a time.

var count = 0;
function update() {
    // do something
    if (++count < 1000)
        setTimeout(update, 500);
    // else everything is done
}
update();

Also, if you intend to create timeouts in a loop, be sure to be familiar with closures and their behavior when accessing counter variables after the loop ran.

Answer

Try

function recurse ( cnt ) {
    for (var i in MenuData) {
        $("#Menu").append('<div style="position:relative; left:' + MenuData[i].x + 'px; top:' + PositionArray[i] + 'px; ">123</div>');
    }
    if (cnt < 1000){
       setTimeout(function () { recurse(cnt + 1); }, 500);
    }
}

$("#Menu").html('');
if (PositionArray[count] != null) {
    PositionArray[count]++;
} else {
    PositionArray[count] = 0;
}
recurse(0);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.