Racing condition when setting value on selectpicker selector

61 Views Asked by At

Looking for an explanation rather than a solution.

I'm facing a situation where updating the selected value and then refreshing the selectpicker as per this SO post suggest doesn't work properly.

Here is my code:

$('[name="city"]', form).val(subscription.city || '');                    // <input>
$('[name="province"]', form).val(subscription.province);                  // <select>
$('[name="locale"]', form).val(subscription.locale || defaultLocale);     // <select>

$('select', form).selectpicker('refresh');

Strangely on some system the last statement setting doesn't pick the value set for locale. Encapsulating the last statement within a setTimeout solve the problem.

setTimeout(function(){
    $('select', form).selectpicker('refresh');
}, 10);

I am aware JavaScript is event driven and an asynchronous language, but doesn't basic statement like those in my example gets executed synchronously?

Although it solves the issue, I find this "hacky" as I have dozens of places where this type of situation occurs.

Update

I discovered that encapsulating the statement in a setTimeout actually didn't always worked.
But, refreshing the page while holding the Ctrl key, worked. Something I have to figure out. I was wrong.

I also found the reason for the "on some system". The system showing the misbehaviour is the one for the production environment. Why this one? Because on this system there are other script being loaded for analytics and marketing strategy.

I found a script from MsDynamics when commented/omitted, the misbehaviour above is gone and all works good. I now need to find out what in this piece of code is messing with mine.

1

There are 1 best solutions below

0
gzmo On

Used Dom modification breakpoints and console.log as suggested by Barmar, and I can see the locale select value being set correctly. It's really when the selectpicker('refresh') is called that it's not always working.

After comparing code loaded on the production server and removing them one-by-one, I could narrow down the cause of the misbehaviour to one script from Azure.

Adding this to the header causes the issue 4-5 time out 10.

<script src="https://mktdplp102cdn.azureedge.net/public/latest/js/form-loader.js?v=1.65.1064.0"></script>

Removing it and I have no more misbehaviour and a 10/10 correct result.

Totally beats me what's in this obfuscated script that could interfere with my code. I do not have the proper knowledge to do such investigation. Maybe someone do. I can give access to a staging server with the issue for those wishing to dig.

Thankfully my client doesn't need it anymore. But I would love to know why...