How to detect when a specific global variable is set

I’ve seen people come across this problem and they usually solve it with a setInterval. When the callback for the setInterval runs, it checks if the global variable is set and if it is, it would clear the interval. Some downsides to this approach are that the code does not react immediately to when the global variable is set, and that you would want to clear the interval if it has run too many times (because it is likely the global variable will not be set).

An alternative to using a setInterval would be to create a setter on the variable you want to respond to when it is set and remove the setter once the value has been set, like this:

Object.defineProperty(window, 'global_variable_name_here', {
  configurable: true,
  enumerable: false,
  set: function(value) {
    // The delete command removes the setter.
    delete window.global_variable_name_here;
    window.global_variable_name_here = value;
    console.log("global_variable_name_here variable is now set, let's do something with it");
  }
});

The above code would use less resources than the setInterval approach, since it would only run if and only if the global variable gets set.

If you wanted that code in a function, here you go:

/**
 * Execute a function when a property on an object has been assigned/set.
 * 
 * @param {String} name The name of the property to watch for being assigned/set.
 * @param {Function} callback The function to execute
 * @param {Object} root The object which will have the property assigned/set.
 */
function call_when_set(name, callback, root = window) {
  Object.defineProperty(root, name, {
    configurable: true,
    enumerable: false,
    set: function(value) {
      // The delete command removes the setter.
      delete root[name];
      root[name] = value;
      callback.call(undefined, value);
    }
  });
}