开发者

Javascript for loop problems

So I have the following code which i basically just a JSON string I am using eval to convert to an object. Now, this object has an array of elements that gets displayed to the screen via a for loop:

function DisplayListing(str)
{
    var obj = eval("(" + str + ")");
    var div = document.getElementById('Response');
    for(i=0; i<obj.files.length; i++)
    {
        div.innerHTML += '<span id="listing' + i + '" class="displayNone"><img src="' + obj.files[i].icon + '"/>' + obj.files[i].name + '</span><br />';   
    }   
}

This works just fine. However, what I want it to do is wait a set interval of time before it continues to the next element. I want to it basically call a function wit开发者_如何学运维h a timeout, so each element fades onto the screen individually. All attempts so far on cause the last element to execute a function. Any help would be greatly appreciated!


http://jsfiddle.net/SfKNc/

var obj = {files: [1, 2, 3]}; // sample object - use JSON.parse by the way
var div = document.getElementById('Response');
for(var i=0; i<obj.files.length; i++) { // use var!
    setTimeout((function(i) {
        return function() { // i changes, so create a new function in which i does not change
            div.innerHTML += 
                '<span id="listing' + i + 
                '" class="displayNone">' + i + 
                '</span><br />';
        };
    })(i), i * 1000); // set timeout to 1000 ms for first item, 2000 for second etc.
}   


you have manually create a sleep function something like the below:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

or you create an empty function and use the setTimeout on it

  function sleep()
    {
    setTimeout(Func1, 3000);
    }

    Func1(){}

http://www.phpied.com/sleep-in-javascript/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜