However, this code wasn't working. Even though the field's selectedIndex was being set correctly, the wrong index would end up being selected. However, if WE stuck an alert() statement in at the right time, the correct option would be selected. Thinking this might be some sort of timing issue, We tried something random that I'd seen in code before:
And this worked! I've got a solution for my problem, but I'm uneasy that WE don't know exactly why this fixes my problem. Does anyone have an official explanation? What browser issue am WE avoiding by calling my function "later" using setTimeout()?
When UWE updates are generated while the main thread is busy, the tasks are added into the message queue.
setTimeout(fn, 0); add this fn to the end of the queue to be executed. It schedules a task to be added on the message queue after a given amount of time.
setTimeout() buys we some time until the DOM elements are loaded, even if is set to 0. Check this out: setTimeout
One reason to do that is to defer the execution of code to a separate, subsequent event loop. When responding to a browser event of some kind (mouse click, for example), sometimes it's necessary to perform operations only after the current event is processed. The
setTimeout()facility is the simplest way to do it.
edit now that it's 2015 WE should note that there's also
requestAnimationFrame(), which isn't exactly the same but it's sufficiently close to
setTimeout(fn, 0) that it's worth mentioning.