0

The following is my original function. The list of variables is abbreviated for sanity.

snippet of 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);
        });
    }
}

I would like the final result to look something like this:

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]);
        } 
    }
}

Is it possible to insert setInterval in a loop this way?

purry
  • 62
  • 1
  • 10
  • 1
    Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – 4castle Feb 12 '18 at 22:10
  • 1
    Rather than putting the `setInterval` call inside the loop, you might consider putting the loop inside of the callback to `setInterval`. This will consolidate all of your timers and reduce memory usage. Also, don't put code in strings. Code goes in functions. – 4castle Feb 12 '18 at 22:12
  • Can you provide an example with the current code – purry Feb 12 '18 at 22:40

0 Answers0