1

I have been meaning to read the entire ECMA5-6 spec, cough, but maybe y'all can help me instead!

Can a variable be changed from "the outside" over the course of execution of a single call in JavaScript?

Pseudo-javascript example:

window.foo = true;

startSomeLoopMutatingFoo();

function f() { 
   var a = window.foo;

   // Insert long, blocking work here, none of which mutates window.foo

   var b = window.foo; // again

   if (a != b) { totalMindExplosion() }
}

Will my mind be blown? Could totalMindExplosion() be called under any conceivable circumstance?

Here's a JS fiddle to facilitate mind fracking: http://jsfiddle.net/Mf3rc/

I'm looking for resources to learn about when asynchronous methods are executed, direct answers, or questions of clarity.

Thanks SO!

Reed Spool
  • 843
  • 7
  • 15
  • 4
    JavaScript is single threaded. While `f` runs, no other code is executed (unless of course called by `f`). Maybe this helps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop and http://stackoverflow.com/q/2734025/218196 – Felix Kling Jun 20 '14 at 04:34
  • 1
    you said blocking work which means if something in that 'work' decides to assign some value then yes value would be different. As it was changed. There was no variable inside function's scope so only var was global and that was changed. – Muhammad Umer Jun 20 '14 at 04:54
  • Updated to remove that case. You are 100% correct but that's not what I was after. – Reed Spool Jun 20 '14 at 05:06
  • it depends on what window.foo is: if it's a getter for performance.now(), then yeah, it can change... – dandavis Jun 20 '14 at 05:19

2 Answers2

1

No, totalMindExplosion() will NOT be called.

When executed, code in a closure (function) blocks the process, there is no chance to execute other code.

Example:

function(){
    var a = 1;
    window.setTimeOut(function(){console.log(a);}, 0);
    a = 2;
}()

This will log 2 instead of 1, even the timeout is 0 second. The console.log function is called only after the full function is executed, by that time, variable 'a' has been set to 2.

David Lin
  • 13,168
  • 5
  • 46
  • 46
0

From the link in the timely comment above, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop

"Run-to-completion"

Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it can be stopped at any point to run some other code in another thread.

So this means my mind will never be blown!

Reed Spool
  • 843
  • 7
  • 15