As stated in the official documentation:
When setTimeout() is called, the code within it runs in a separate environment compared to the function that invoked it. This results in the this keyword referring to the window (or global) object rather than the original function's this value.
:
Both examples illustrate how the scope of timeout code is linked to the global context, specifically window
.
In the first scenario, the specific context is insignificant because obj.style.display
is not assessed until the timeout activates. By that point, obj
retains its initial value set by dismiss
, ensuring smooth execution.
In contrast, the second example executes the code immediately, meaning that obj
remains undefined within the global window
scope (or if defined, it may not align with expectations). Essentially, this leads to the following situation:
function dismiss(obj) {setTimeout(function () { undefined = "none" }, 20);}