Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run code in JavaScript, only when a variable is defined?

Tags:

javascript

I'm writing a simple function in JavaScript:

function waitThenRun(objectToWaitFor, callback) {
   // logic to periodically check for objectToWaitFor to become something
   // then call the callback
}

And I intend to use it as:

waitThenRun(someObjectThatWillBeDefinedLater, function() {
    // Doing something with someObjectThatWillBeDefinedLater
});

Yet I get this error:

Uncaught ReferenceError: someObjectThatWillBeDefinedLater is not defined

How do you handle this?

In simpler terms, I want to run a piece of code only when a global JSON variable is defined, and I can't determine when and where it gets defined. Sometimes it gets defined after my code, sometimes before my code, sometimes a second later, sometimes 5 seconds later. It's non-deterministic.

like image 562
Truth Pursuer Avatar asked Jun 16 '26 09:06

Truth Pursuer


1 Answers

You can dispatch an event on the window when you define your JSON Object and add an event listener for that event on the window. This way, you will not need to use a setInterval to continuously check if a global variable is defined.

function defineJSON(){
  window.JSONObj = {x: "something"};
  triggerEvent("JSONDefined", window, {JSONObjName: "JSONObj"});//fire a custom event on the window when you define the JSON Object
}
function triggerEvent(type, obj, data){
  var ev;
  if (document.createEvent) {
    ev = document.createEvent("HTMLEvents");
    ev.initEvent(type, true, true);
  } else {
    ev = document.createEventObject();
    ev.eventType = type;
  }
  ev.eventName = type;
  if(data){
   for(var key in data){
     if(data.hasOwnProperty(key)){
        ev[key] = data[key];
     }
   }
  }
  if (document.createEvent) {
    obj.dispatchEvent(ev);
  } else {
    obj.fireEvent("on" + ev.eventType, ev);//for < IE8
  }
}
window.addEventListener("JSONDefined", function(ev){
  //this event handler will be called when the JSON Object is defined
  console.log("JSON defined:", window[ev.JSONObjName]);
});
setTimeout(function(){
   defineJSON();
}, 2000);//define JSON Object after 2 seconds (just for this example)
like image 130
Unmitigated Avatar answered Jun 17 '26 22:06

Unmitigated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!