JavaScript:在另一个setTimeOut(嵌套的setTimeOut)内设置setTimeOut来刺激API响应不起作用

时间:2018-10-18 13:02:56

标签: javascript jquery angular mocking settimeout

要求:用户在文本框中连续扫描作业编号,没有任何延迟。对于每个作业编号,我需要在后台调用API以获取扫描作业编号的详细信息。

我所做的事情: 我写了一个小的模拟代码来激发这种需求。 我使用setTimeOuts延迟用户扫描和延迟API响应

问题: 延迟扫描工作正常,但延迟API响应无效。

jsbin链接 code in jsbin

请运行以下代码并检查控制台。

var dataset = [10, 20, 30];
var delay = 100;
var apiDelay = 3000;



function execute(dataset) {    
    var i = 0;
    scannedJob(dataset, i);
}


//1ST TIME OUT METHOD//
function scannedJob(dataset, i) {

    setTimeout(function() {
              console.log("Scanned Job Number ="+dataset[i]+" @  time = " + new Date().toLocaleTimeString());


        fireJobSearchHttpAPI1(dataset[i]);

        i++;

        if (dataset.length > i) {
            self.scannedJob(dataset, i);
        } else {
            i = 0;
        }
    }, delay);
}

//2nd TIME OUT METHOD//

/* TWO TYPES OF METHODS I WRITTEN , BOTH ARE NOT WORKING,
EXPECTED:  Each API call should fire with 5sec delay. Instead all 3 api calls given response after 5 seconds. I need each call should take 5sec and total at the end it should take 15 seconds., 
BUT FIRING ALL THE JOB NUMBERS IMMEDIATELY WITHOUT DELAY
*/
function fireJobSearchHttpAPI1(jobNum) {
        setTimeout(function() {
            console.log("job number '"+jobNum+"' API FIRED @ " + new Date().toLocaleTimeString());
        }, apiDelay);

}


function fireJobSearchHttpAPI2(jobNum) {
    (function myLoop(i) {
        setTimeout(function() {
            console.log("job number '"+jobNum+"' API FIRED  @ " + new Date().toLocaleTimeString());
           if (--i) myLoop(i);
        }, apiDelay)
    })(1);

}


//Main Method
execute(dataset);

1 个答案:

答案 0 :(得分:1)

您需要将当前`{"bus":{ "passengers[0]":{"name":"John","familiName":"Smith"}, "passengers[1]":{"name":"Marry","familiName":"James"} }}` 作为参数传递,因此您需要将该索引乘以当前api调用延迟,因此第一步是(index = 0),所以您应该执行类似index的操作,则应为5000,第二步,索引将为1,然后(index + 1) * apiDelay将为10000,最后一步(index + 1) * apiDelay将为2,然后为{{1 }}为15000。

在底部,对当前代码进行了一些修改。

index