Strange behaviour in a simple JS function

I have an icon bar which calls appropriate functions. The icons are with onclick() set to call the appropriate function for that icon. All working nicely.

I just added an icon, same pattern as the others.

<a href="#"><i class="fa fa-flash" onclick="reveal()" title="Reveal the current answer"></i></a>

The script contains …

function reveal() {
    alert("Here");
    console.log(`Revealing answer : ${gb.csrClue}`);
    gb.revealClue(gb.csrClue);
    return false;
}

gb is a singleton object created on startup.

Here’s what’s weird – if the alert is there, all works perfectly. If I comment out the alert (and make no other changes) the function does nothing.

If I comment out the alert and put a breakpoint on the console.log (or the call to gb.reveal) I can step through the behaviour and watch everything work perfectly. The code completes and the clue is revealed.

Without the breakpoint and with no alert, nothing happens. Nothing logged to the console (either from reveal() or from gb.revealClue()) and nothing updated on the page.

I’m using Visual Studio Code in debugging mode – I might have put this down to some weird bug, but if I commit this change the behaviour is the same on the site.

Very odd – can’t wrap my head around this one.

  • 3

    Most likely async problem. When the function runs gb is probably not initialised. alet pauses the execution.

    – 

  • For sure this is an async issue, there are all the symptoms. Try waiting a minute before clicking your button

    – 

  • are you fetching data from server through gb ? most likely gb is not initialised at the point of click. placing an alert / debug creates the time space to have it completed / initilized. Ensure gb is initialized properly before you click or before the reveal method is called

    – 




  • Thanks for comments. “gb” object triggers an async fetch, which calls back into the object to JSON.parse and display the loaded data (or error). However that completes before the build() function adds the grid of buttons and the menu items are disabled until build() completes. For completeness, I waited 10 seconds and tried again with the same issue. I’ve changed the design so the header is a button bar instead of links. Same functions are called onclick – the problem doesn’t occur now. So it’s fixed, but obviously still kinda confused as to why it happened.

    – 




Leave a Comment