Stimulus Discourse

Recursion in a Controller?


Any suggestions on how I’d get recursion to work on initialize?

I’m trying to call a function with initialize() that will check to see if an outside library (Google Maps API) is loaded yet, and if it is, call a function related to it, and if it’s not, wait 500ms, then call itself again to see if the library is loaded yet.

So far, no luck. Am I missing something?

initialize() {
  whenGoogleLoadedDo() {
    if (typeof google != 'undefined')
      setTimeout(function () {
        console.log('setTimeout Called')
      }, 500)

  initAutocomplete() {
    autocomplete = new google.maps.places.Autocomplete(
      /** @type {!HTMLInputElement} */
      // (document.getElementById('autocomplete')), {});
      this.autocompleteTarget, {});

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', () => {


Here are two options:

On initialize, use a setTimeout to wait that long, and if it’s not available, launch another setTimeout.

Or for google maps specifically: there’s bound to be an event triggered when it’s available. In which case, on initialize, you could listen for that event using a custom addEventListener that you would discard manually on your controller’s disconnect(), or better yet, use the @window context for an action to define the event listener at the level of the controller’s markup.