Javascript/jQuery - setInterval stopping execution of other Javascript functions

Asked

Viewed 55 times

0

I’m facing a problem that’s driving me crazy already. It’s like this.

I am capturing json data from an external server on cross-Omain, I need this data updated every 5 seconds. I was able to loop and let this function run. However, I have a button on the same page, that when it is at the time of setInterval, the button simply does not work. I would like to know an alternative to loop, keeping up to date and not lose the other functions of Javascript while setInterval is running.

From now on, thank you.

Test function:

/* DEFINIÇÕES DE VARIÁVEIS */
var lightStatus;

function toggleLight(lightState){
    
    $.post("http://192.168.0.109/LED", {}, function(){
        
    });
    
    
    if(lightState){
        lightStatus = false;
    } else {
        lightStatus = true;
    }
    console.log("Status: " + lightStatus);
}

setInterval("updateSensors()", 5000);

function updateSensors(){
    $.post("http://192.168.0.109/sensors", {}, function(ESP8266){
            //console.log(data);
            lightStatus = ESP8266.lightStatus;
            console.log("lightStatus> " +ESP8266.lightStatus);
            console.log("Temperatura> " +ESP8266.temperatura);
            console.log("Umidade> "+ ESP8266.umidadeAr);
            //console.log("Umidade do solo> "+ ESP8266.umidadeSolo);
        }, "json");
}

$(function(){
    
    updateSensors();
    
    console.log("var lightStatus: "+lightStatus);
    
    $("div#lightSwitch").on("click", function(){
        toggleLight(lightStatus);
    })
    
    
    
});
  • setInterval takes two arguments as paremtro, the first is a function and the second time, you are passing a string that is the name of your function is time, and is probably generating some error in your console. Try to pass something like setInterval(updateSensors, 5000) quote-free

  • Actually that setInterval works yes. In case it will pass the string in a eval. However Ellysson, it would really be better if you wrote setInterval(updateSensors, 5000);.

  • Ellysson, what happens is that the page freezes every 5 seconds (case 1) or only that button does not work after the first call from updateSensors (case 2)?

  • If it is case 1, you have some other routine there that takes a lot of execution time. You should improve it or you can even put a little asynchronicity not to lock the main loop for noticeable time. OR you can put the heavy code in a WebWorker.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.