如何在循环中设置setInterval?

时间:2018-02-12 22:06:57

标签: javascript window

以下是我原来的功能。变量列表缩写为sanity。

main.js的片段

var loopPower = [];
var loopCurrentRequest;

function intervalManager(flag , timer) {
    if (flag) {
        loopPower["#fwdPwr"] = setInterval(function(){getPWR("#fwdPwr");}, timer);
        loopPower["#revPwr"] = setInterval(function(){getPWR("#revPwr");}, timer);
        loopCurrent = setInterval(function(){getAndSetCurrent();}, timer);
    }
    else
    {
        clearInterval(loopPower["#fwdPwr"]);
        clearInterval(loopPower["#revPwr"]);
        clearInterval(loopCurrentRequest);
    }
}

function getAndSetCurrent(){
        $.ajax({
            url: "some_url",
            type: "GET"
        }).done(function(data) {
            $("#current").html(data[0]);
        }).fail(function(data,textStatus,errorThrown) {
            clearInterval(loopCurrentRequest);
        });
    }
}

我希望最终结果看起来像这样:

newMain.js

loopSet = {
    loopPower['#fwdPwr'] : "getPWR('#fwdPwr')",
    loopPower['#revPwr'] : "getPWR('#revPwr')",
    loopTxDataBusRequest : "getCurrent()"
}

function intervalManager(flag , timer) {
    if (flag) {
        for (var varLoop in loopSet) {
            varLoop = setInterval(function(){loopSet[varLoop]}, timer);
        } 
    }
    else
    {
        for (var varLoop in loopSet) {
            clearInterval(loopSet[varLoop]);
        } 
    }
}

是否可以通过这种方式在循环中插入setInterval?

0 个答案:

没有答案