Angelika S Michel Angelika S Michel - 6 months ago 8
Javascript Question

Jquery do something every few seconds unless all values in object are true



I have this code:

var obj = {
eins : false,
zwei : false,
drei : false
};

$.each(obj, function (k, v) {
if (!v) {
console.log(false);
}
});


Now what I am trying to do is the following: Check if all of the values in the obj are true. If they are do this, if they are not, try again.

I tried messing with setInterval and $.each but couldn't manage to make it run synchronously..

What I tried:


var lPageFullyLoaded = function () {
var lAllInited = true;
$.each($scope.initializedActions, function (k, v) {
if (!v) {
lAllInited = false;
}

if (!lAllInited) {
return false;
}
});

return true;
}

var lChecker = setInterval(function () {
if (lPageFullyLoaded()){
// Do what needs to be done
clearInterval(lChecker);
}
}, 300);

Answer

Simple loop to see if the object is all true and an if/else to determine the step is all that is needed.

var obj = { 
    eins : false,
    zwei : false,
    drei : false
}; 

//function to call to see if code is updated
function check () {

  //Check to see that every property in the object is true
  var isValid = Object.keys(obj).every( function (key) {
    return obj[key];
  });
  
  //if true, do what you need to do
  if(isValid) {
      document.body.style.backgroundColor = "green";  
  } else {  //not true, than run check again
      window.setTimeout(check, 500); //next check is half a second 
  }
  
}

check();  //initialize the checking

//A way to flip the data for the demo
document.querySelector("button").addEventListener("click", function () {
    obj = { 
        eins : true,
        zwei : true,
        drei : true
    };
});
<button>Set</button>