Jacques Koekemoer
Jacques Koekemoer

Reputation: 1414

window.settimeout in javascript loading too fast

I have this js code that has to make the height of a panel bigger on load of my page. But it seems to be loading it way too fast.

var TimerID;

function LoadDoc() {
    for(i=0;i<=100;i++){    
        TimerID=window.setTimeout(MoveRolldownDown(i),5000);
    }
}

function MoveRolldownDown(i){
    document.getElementById('Rolldown').style.height=i + '%';
    window.clearTimeout(TimerID);
}

This loads in the page nearly instantly, so how can i make this load slower. At the top of my HTML page i have this code

document.onreadystatechange = function () {
    if(document.readyState === "complete"){
        LoadDoc();
    }
}  

Upvotes: 1

Views: 1375

Answers (2)

Naftali
Naftali

Reputation: 146302

1st thing -- your functions are executing immediately so you need to put them inside of another function.

One more thing -- all of your timeouts end at basically the same time!

Try something like this:

function LoadDoc() {
    for (i = 0; i <= 100; i++) {
        var down = i;
        setTimeout((function (down) {
            return function(){ //return function for timeout
                MoveRolldownDown(down);
            };
        })(i), 10 * i);
    }
}

function MoveRolldownDown(i) {
    document.getElementById('Rolldown').style.height = i + '%';
}

Demo: http://jsfiddle.net/maniator/RTaZh/

Upvotes: 2

bosspj
bosspj

Reputation: 80

Yes, it because you are calling the function within the parameters,

You probably want something like

window.setTimeout(MoveRolldownDown,5000, [i]);

https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout

Upvotes: -1

Related Questions