[OpenLayers-Dev] threading/synchronicity in javascript

Tim Schaub tschaub at opengeo.org
Mon Nov 3 23:40:07 EST 2008


Hey-

Erik Uzureau wrote:
> Dear OpenLayers users & dev,
> 
> Pardon the non-geo post, but I am wondering if anyone out there has come 
> up across issues with
> synchronicity in javascript?
> 
> After pouring over this stuff for several hours, I think I am pretty 
> resolved to just say "ok, javascript
> is event-driven and not truly multithreaded, so there is no need to worry".
> 
> In the off-chance that someone out there might have information 
> otherwise, please let me know.

I think the clearest answer is that event listeners and "functions like 
setTimeout() and asynchronous callbacks need to wait for the script 
engine to sleep before they're able to run."

Maybe you're concerned about something else, but if you're wondering 
whether a sequence of event handling code can be executed again before 
it has finished, the answer is no.

Again, maybe you're reading up on mutexes for something else, but here's 
some code that demonstrates that you can't change the "current" value 
with subsequent triggers of the same event while the event handling code 
is executing, no matter how long it takes to run.

function check(iter) {
     var current;
     document.body.onmousemove = function() {
         var start = (new Date).getTime();
         var id = start + Math.random();
         current = id;
         // do something that takes a while
         var a = [];
         for(var i=0; i<iter; ++i) {
             a.push(i);
         }
         var end = (new Date).getTime();
         console.log(
             id + " start: " + start + " end: " + end +
             " elapsed: " + (end - start)
         );
         if(current != id) {
             console.error(id + " failed");
         }
     }
}

// loop runs in <1ms, events fired every ~17ms
check(1000);  // wiggle mouse over body

// loop runs in ~25ms, events fired every ~45ms
check(100000);

// loop runs in ~225ms, events fired every ~250ms
check(100000);

You can do the same sort of thing with setTimeout.

Tim

> 
> Below are two of the links that have fed my brain for the last few hours:
> 
> debate:
> http://stackoverflow.com/questions/124764/are-mutexes-needed-in-javascript
> 
> implementation of a mutex in js:
> http://www.developer.com/lang/jscript/article.php/3592016
> (note that his actual code for this *only* runs in ie, which obviously 
> docks it a fair amount of credit)
> 
> cheers,
> erik
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Dev mailing list
> Dev at openlayers.org
> http://openlayers.org/mailman/listinfo/dev


-- 
Tim Schaub
OpenGeo - http://opengeo.org
Expert service straight from the developers.



More information about the Dev mailing list