带有计时器的Javascript更新表(隐藏在csv文件中)

时间:2016-05-18 14:19:19

标签: javascript arrays csv

大家。我有一个有趣的问题。非常感谢你的帮助。致力于解决一项任务:

  

使用提供的初始CSV数据实施财务报价单网格   图

     

将snapshot.csv中的数据加载并解析为模型。

     

将基于该数据的网格渲染到DOM。

     

编写引擎以通过deltas.csv工作并向其发出更新消息   解析。

     

当一行只存在一个数字时,该时间量为   应该等待毫秒,直到处理下一组增量。   处理完最后一组增量时,返回到开头   档案并重复。

     

每组增量应合并到现有数据集中   尽可能以最有效的方式传播到DOM。

     

通过视觉闪光提供项目已更新的通知   在用户界面。

我的路径: 我设法加载snapshot.csv,解析它,创建表,然后(使用promises),上传第二个文件delta.csv,解析它,尝试更新表,但努力创建计时器功能来更新表根据delta csv文件中的毫秒数量。提前感谢您的建议))我正在学习javascript,并寻找挑战,这看起来很有趣。



function CSVToArray( strData, strDelimiter ){
  strDelimiter = (strDelimiter || ",");
  var objPattern = new RegExp(
      (
          // Delimiters.
          "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

          // Quoted fields.
          "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

          // Standard fields.
          "([^\"\\" + strDelimiter + "\\r\\n]*))"
      ),
      "gi"
      );
  var arrData = [[]];
  var arrMatches = null;
  while (arrMatches = objPattern.exec( strData )){
      var strMatchedDelimiter = arrMatches[ 1 ];
      if (
          strMatchedDelimiter.length &&
          strMatchedDelimiter !== strDelimiter
          ){
          arrData.push( [] );
      }
      var strMatchedValue;
      if (arrMatches[ 2 ]){
          strMatchedValue = arrMatches[ 2 ].replace(
              new RegExp( "\"\"", "g" ),
              "\""
              );
      } else {
          // We found a non-quoted value.
          strMatchedValue = arrMatches[ 3 ];
      }
      arrData[ arrData.length - 1 ].push( strMatchedValue );
  }

  // Return the parsed data.
  return( arrData );
    }

function httpGet(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = function() {
      if (this.status == 200) {
        resolve(this.response);
      } else {
        var error = new Error(this.statusText);
        error.code = this.status;
        reject(error);
      }
    };
    xhr.onerror = function() {
      reject(new Error("Network Error"));
    };
    xhr.send();
  });

}

var r1,r2
httpGet('snapshot.csv').then(function(result) {
  r1 = CSVToArray(result);
  createTable(r1);
  return httpGet('deltas.csv')
}).then(function(result2) {
     r2 = CSVToArray(result2);
     updateTable(r2)
   });

var hInterval = null;
var k = 0;
var iteration=0;
function updateTable(how) {
    var myTable = document.getElementById('myTable');
    var j=1;
    var watch_dog=0;
    var x = document.getElementById("myTable").rows[0].cells;
    console.log(x);
    while(j<myTable.rows.length) {

        if (typeof(how[k]) !== "undefined") { //

            var startPos = 2; //In file we have broken data (some time 6 columns some time 5)
            if (how[k].length === 5)
                startPos = 1;

            var valueAdded=0; //How much value changed
            for (var i = startPos; i < startPos + 3; i++) {

                var value = how[k][i];

                if (typeof(value) !== "undefined") {
                    valueAdded++;
                    if (value.length > 0) {
                        if (startPos === 2)
                            myTable.rows[j].cells[i].innerHTML = value;
                        else
                            myTable.rows[j].cells[i + 1].innerHTML = value;
                    }
                }
            }

            if (valueAdded>0) //if some values changed we are increment j
             j++;

            k++; //Increment global row pointer


        } else {
            //Restart when we finished
           iteration=1;
            k=0;
            break;
        }
    }
}


function createTable(now) {
 var body = document.getElementsByTagName("body")[0];
    // create elements <table> and a <tbody>
    var tbl     = document.createElement("table");
    var tblBody = document.createElement("tbody");
    tbl.setAttribute("id","myTable");
    // cells creation
    for (var j = 0; j < now.length-1; j++) {
        // table row creation
        var row = document.createElement("tr");

        for (var i = 0; i < now[0].length; i++) {
            // create element <td> and text node
            //Make text node the contents of <td> element
            // put <td> at end of the table row
            var cell = document.createElement("td");
            var cellText = document.createTextNode(now[j][i]);

            cell.appendChild(cellText);
            row.appendChild(cell);
        }

        //row added to end of table body
        tblBody.appendChild(row);
    }

    // append the <tbody> inside the <table>
    tbl.appendChild(tblBody);
    // put <table> in the <body>
    body.appendChild(tbl);
    // tbl border attribute to
    tbl.setAttribute("border", "2");
}
&#13;
<!DOCTYPE html>
<html>
	<head>
		<title>Application</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	    <meta name="description" content="Demo project">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
		<link rel="stylesheet" href="styles.css">
		<style type="text/css"></style>
	</head>
	<body>
		<p>Let the game begin!</p>
	</body>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
	<script type="text/javascript" src="script.js"></script>
</html>
&#13;
&#13;
&#13;

项目文件: https://dw3i9sxi97owk.cloudfront.net/uploads/jobAttachments/150928161919_pph.zip

1 个答案:

答案 0 :(得分:1)

您可以编写一个递归函数,一次处理一行,然后设置超时以在X秒内处理下一行。下面的代码只是伪的,它不使用你的变量或任何东西......但希望你能从中得到这个想法。它是一个递归函数,在等待一段时间后调用自己的下一行。

function processRow(row, waitTime) {
    setTimeout(function() {
        //do your row stuff here

        //move on to the next row, look at it's wait time and pass that along
        var nextRow = row+1,
            nextWaitTime = nextRow.waitTime;
        processRow(nextRow, nextWaitTime);
    }, waitTime);
}

//run the first instance
var firstRow = 1,
    firstWait = firstRow.wait;
processRow(firstRow, firstWait);