我多年来一直使用JavaScript作为工具,但直到最近我才开始用它编写应用程序。看完Crockford on JavaScript - Level 6: Loopage后,我开始欣赏事件循环和不阻挡的风格。为了更好地掌握这一点,我回到了一个应用程序,我相信我的代码设计很糟糕。
应用程序下载一个包含~20个元素的~45KB JSON文件(缩小,未压缩),因此平均每个元素有大约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()
次调用之间下载的话,这将失败,因为数组长度可能会改变,无论数据组是否来自同一个数组。
答案 0 :(得分: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);