0

多年来,我一直使用 JavaScript 作为工具,但直到最近我才开始使用它编写应用程序。在看了Crockford on JavaScript - Level 6: Loopage 之后,我开始欣赏 Event Loop 和不阻塞的风格。为了更好地掌握这一点,我回到了一个应用程序,我相信我有一个设计糟糕的代码区域。

该应用程序下载了一个约 45KB 的 JSON 文件(已压缩、未压缩),其中包含约 20 个元素,因此平均每个元素具有约 2.25KB 的数据。下载每分钟进行一次,并且手动触发,此时新阵列替换旧阵列。每 15 秒清除一次 DOM 并迭代数组。对数据执行计算和逻辑以创建要插入到 DOM 中的 DOM 元素组。

而不是这样做:

for (int i = 0; i < array.length; i++) {
  // Perform logic
}

我将如何以无阻塞的方式实现它?到目前为止,我想出了:

var performLogic = function performLogic(element) {
  // Perform logic
}

var counter = 0;
var iterator = function iterator() {
  counter += 1
  if (counter < array.length) {
    performLogic(array[counter]);
    setTimeout(iterator, 0);
  }
}

setTimeout(function() {
  counter = 0;
  iterator();
}, 0);

我无法理解它。我知道如果在调用之间下载了数据,这将失败performLogic(),因为数组长度可能会改变,无论数据组不会来自同一个数组。

4

1 回答 1

1
var arrayData=[], // current data array for performing logic
    newArrayData=[], // new downloaded data array for performing logic
    arrayDataIndex=0;

var doAjaxRequest=function(fCallback){
  // here must be placed code which doing request for downloading data. "~45KB JSON file"
  // if success calling fCallback function and passing data.
};

var genNewDataArray=function(data){
  // here must be placed code which converts and saves "data" variable value 
  // into "newArrayData" variable value. For example:
  //   newArrayData = convertDataIntoArrayData(data);
  // next calling:
  setTimeout(newDataArrayLoaded,0);
  // or can be simply calling newDataArrayLoaded(); without setTimeout
};

var newDataArrayLoaded=function(){
  if(arrayDataIndex===0){
    arrayData=newArrayData;
    performLogicForAll();
  }
  else setTimeout(newDataArrayLoaded,0);
};

var performLogicForAll=function(){
  performLogicForOne(arrayData[arrayDataIndex]);
  arrayDataIndex++;
  if(arrayDataIndex===arrayData.length)arrayDataIndex=0;
  else setTimeout(performLogicForAll,0);
};

var performLogicForOne=function(){
};

// loading every 15 seconds a new data with help of setInterval.
// this is not optimized! use another logic in your page.
setInterval(function(){doAjaxRequest(genNewDataArray);},15000);
于 2012-04-04T12:22:29.360 回答