JavaScript setTimeout loop only running twice before returning error:

时间:2015-07-31 19:53:50

标签: javascript jquery html xml settimeout

I've been working on a website that processes XML files, And I ran into an issue once I added a bit more processing. The issue I am having is in using setTimeout to give the browser a break to 'breathe' so that it doesn't crash trying to load a bunch of information into innerHTML. When I load it, it only loops twice, then returns an error of "VM###:1"(### constantly changes).

var i = 0;
    process();
    function process(){
        if (i < x.length) {
            var name = $(x[i]).find("Description[DescriptionCode='DEF']").text();
            var ixx = x.length + (20 - (x.length % 20));
            var ix = Math.round((i+10) / 20);
            var type = "";
            var desc = $(x[i]).find("Description[DescriptionCode='DES']").text();
            var lamp = desc;
            var g = 1;
            var id = $(x[i]).find("PartNumber").text();
            var ddId = "D" + id + "D"
            var price = $(x[i]).find("Pricing[PriceType='RMP']").find("Price").text();
            for (n=0;(g == 1) && (n < sType.length); n++) {
                if (desc.indexOf(sType[n].type) > -1) {
                    type = sType[n].type;
                    lamp = lamp.replace(sType[n].type, '');
                    g = 0;
                }
            };
            for (n=0;(g == 1) && (n < sVolume.length); n++) {
                if (desc.indexOf(sVolume[n].vol) > -1) {
                    vol = sVolume[n].vol;
                    lamp = lamp.replace(sVolume[n].vol, ''); 
                    g = 0;
                }
            };
            for (n=0;(g == 1) && (n < sYear.length); n++) {
                if (desc.indexOf(sYear[n].year) > -1) {
                    year = sYear[n].year;
                    lamp = lamp.replace(sYear[n].year, '');
                    g = 0;
                }
            };

            document.getElementById("productDiv").innerHTML += "The stuff I'm processing goes here.";
            i++;
        setTimeout(process(), 1);
        }
    };

1 个答案:

答案 0 :(得分:1)

您正在调用setTimeout内的process函数:

setTimeout(process(), 1);

由于process没有返回任何内容(与函数相反),因此不会产生任何预期的效果 - 更不用说你正在寻找的效果了。此外,在Chrome中,这样做会使浏览器无响应。

您希望传递对稍后执行的函数的引用:

setTimeout(process, 1);