Skip to content

Instantly share code, notes, and snippets.

@sixthgear
Created December 16, 2011 00:57
Show Gist options
  • Select an option

  • Save sixthgear/1483856 to your computer and use it in GitHub Desktop.

Select an option

Save sixthgear/1483856 to your computer and use it in GitHub Desktop.
var events = [];
var intervals = [];
var max_id = 0;
function setInterval(callback, period) {
intervals.push(new Interval(callback, period));
return ++max_id;
}
function clearInterval(id) {
intervals.splice(id, 1);
}
function eventLoop() {
var dt;
var this_time;
var prev_time;
while (true) {
// calculate dt
this_time = Date.getTime();
dt = this_time - prev_time;
prev_time = this_time;
// process event stack
while(events) {
var e = events.pop();
e.callback(e.event);
}
// process timeouts and intervals
for (i in intervals) {
intervals[i].accumulator -= dt;
if (intervals[i].accumulator <= 0) {
intervals[i].callback();
intervals[i].accumulator += intervals[i].period;
}
}
}
}
eventLoop();
@sixthgear

Copy link
Copy Markdown
Author
<sixthgear> this is a simplified version of whats going on behind the 
            scenes in the js interpreter
<sixthgear> everything that happens in js for the most part is an event, 
            interval or timeout callback
<sixthgear> that eventLoop() runs for as long as the page is loaded in 
            memory
<sixthgear> hkhalid: imagine your page setup code is part of the windows 
            "onload" event. Well that event is added to the event stack 
            (that code isnt included) and when execution hits line 25,
            the onload function associated with that event is called
<sixthgear> so you do a bunch of stuff in that function, including 
            adding some intervals with setInterval()
<sixthgear> you can see what that code does, it pushes them onto the 
            intervals list
<sixthgear> now once your onload function exits, then the eventLoop is 
            free to start processing your intervals (along with all of 
            the other events and intervals that are set up automatically 
            as part of the ui)
<sixthgear> however, if you enter a loop inside of onload, that function 
            will never exit
<sixthgear> and that means no other code, not even intervals will be 
            fired
<sixthgear> no events will be called for mouse movement, etc
<sixthgear> the js interpreter is effectively locked, because you didnt 
            return
<sixthgear> hkhalid: these are the basoc concepts of "event loops" and 
            asynchronous programming in general. As a bonus you now also 
            understand how tornado and node.js work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment