View Single Post
  #9 (permalink)  
Old June 12th, 2008, 01:24 AM
Old Pedant Old Pedant is offline
Friend of Wrox
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts

Yes, JS is single threaded.

Tell you the truth, I never thought about whether that meant that all execution is suspended when you are doing a call to
    alert( )
but it's easy enough to test.

Let me do so:

var tick = new Date(2008,1,1,0,0,0);

function sillyWayToWait( )
    alert( "first alert: " + tick.toString() + "\nWait 20 seconds before hitting OK");
    alert( "SECOND alert: " + tick.toString() + "\nSee?  time not changed.  Click OK");
    setTimeout( 'alert("but now look:" + tick.toString())', 1 ); // wait 1 millisecond

function changeTick( )
    tick = new Date();
<body onLoad="setTimeout('changeTick( )', 10000);">
<a href="#" onclick="sillyWayToWait();">click me fast!</a>
Try that HTML page. Guess what? Yep, alert() is part of the thread.

Notice how even a 1 millisecond delay, though, allows the postponed event (the timeout() event) to come in and do its job.

So... alert() is a lousy way to debug realtime JS, indeed!

But so is dumping data to a visible area of the screen, because if your JS code "hangs" the redraw of the screen, the visible area can't be updated. (After all, when you do something like
    document.getElemntById("FOO").innerHTML = "BAR";
that doesn't *REALLY* update the screen! It just modifies the DOM representation of it in memory; it's up to the browser's rendering engine to move the pixels around to effect the visible change. And if the rendering engine isn't able to run because you are holding an alert() open...)