javascript - JS - why such order of code execution? (Beginner level) -
what's logic behind order of js code execution? i'd expect after clicking button background become red , message show up. however, message appearing first , color applied background after click ok -> codepen. proper&correct way make background red before click ok?
function run(){ document.body.style.backgroundcolor = 'red'; alert('contratulations!'); }
<html> <head></head> <body> <button onclick="run()">click me!</button> </body> </html>
the code executed in order expect, however, each of statements not synchronous, invoke funcitonality provided webbrowser.
browser executed javascript not occur on ui thread. when change dom (the abstraction allow javascript interact browser html), instead triggers update ui (browser page) occurs separate javascript execution. underlying dom element updated, there non instantaneous update actual ui.
in code, after change dom element, code triggers browser display alert. displaying alerts browser specific behavior, , in case of chrome, pauses ui update, , requires interact alert before continuing. in firefox, alert shown after ui updated.
the behavior between 2 browsers difference in how browser rendering engine , event loops implemented.
function run(){ document.body.style.backgroundcolor = 'red'; settimeout(function() { alert('contratulations!'); },0 ); }
<html> <head></head> <body> <button onclick="run()">click me!</button> </body> </html>
this answer has little more information on how can solve problem, why settimeout(fn, 0) useful?
by calling settimeout
adding alert
display end of javascript event loop, gives ui enough time update.
Comments
Post a Comment