javascript 分时函数 分批次添加DOM节点 timeChunk
创建1000个webqq的qq好友列表, 一个好友用一个节点来表示
* timeChunk
var timeChunk = function(a, fn, sz, done) { var obj, t, len = a.length; var start = function() { for (var i = 0; i < Math.min(sz || 1, a.length); i++) { var obj = a.shift(); fn.call(this, obj); } } return function() { t = setInterval(function() { // 如果全部节点都已经被创建好 if (a.length === 0) { var i = clearInterval(t) typeof done === "function" && done.call(this); return i; } start(); }, 200); } } /** * Pad a string to a certain length with another string */ function str_pad(input, pad_length, pad_string) { var i = String.valueOf()(input); var n = pad_length - i.length; if (n <= 0) return i; var s = pad_string || "0"; while (n--) { i = s + i; } return i; } // test var ary = []; for (var i = 1; i <= 1000; i++) { ary.push(i); } // 每次加载8个 var renderFriendsList = timeChunk(ary, function(n) { var div = document.createElement("div"); div.innerHTML = "Friend-" + str_pad(n, 4); document.body.appendChild(div); }, 8, function() { var hint = document.createElement("p"); hint.innerHTML = "好友列表加载完了"; document.body.insertBefore(hint, document.body.querySelector("script")); }); renderFriendsList();
Run: