タイマーを使ってコストのかかる関数を遅延実行させるfunction swap(items, firstIndex, secondIndex) { var temp = items[firstIndex]; items[firstIndex] = items[secondIndex]; items[secondIndex] = temp; } function bubbleSort(array, onComplete) { var pos = 0; (function () { var j; for (j = array.length; j > pos; j--) { if (array[j] < array[j - 1]) { swap (array, j, j - 1); } } pos++; if (pos < array.length) { setTimeout(arguments.callee, 500); } else { onComplete(array); } })(); } var array = [3,1,4,2]; bubbleSort(array, function (v) { console.log(v)} ); function chunk(array, process, context) { var items = array.concat(); setTimeout(function () { var item = items.shift(); process.call(context, item); if (items.length > 0) { setTimeout(arguments.callee, 100); } }, 100); } var obj = { items : [] }; var items = [ 1,2,3 ]; chunk(items, function (value) { this.items.push( value * 10); }, obj); console.log(obj.items); 出典http://www.slideshare.net/nzakas/writing-efficient-javascript |
|