Skip to main content
GameDev.net gamedev.net
🔒 Locked

Callback is blocking.. (JavaScript)

Started by Oliver Sch Mar 6, 2013 at 5:50 AM 1 replies 2.7k views
Original Post
Oliver Sch
Oliver Sch

I am trying to understand callbacks properly so that I can iterate arrays without blocking the Server.

Please tell me why it is blocking.. what am I doing wrong? I would much rather run this loop, and then do something when it is finished, but not block the rest of the server.

Here is the code:


//callback test

var myID = 666;
var grid = [
    [0,0,0],
    [0,0,0],
    [0,0,0]
];


function find_empty_slot(id,callback){
    console.log("Your ID is" + id);
    callback();       
}

find_empty_slot(myID,function(){
    for(var y = 0, len = grid.length; y < len; y++){
        for(var x = 0; x < grid[y].length; x++){
            if(grid[y][x] === 0){
                console.log("I am a Callback");
            }
        }
    }
});

console.log("This should fire before the Callback?");
Oliver Sch
Oliver Sch

console.log("This should fire before the Callback?"); should fire before the callback.. but it doesnt..

y2kiah
y2kiah
It's blocking because you're telling it to block by running a tight loop, and it's behaving exactly the way you wrote it. You might be under the impression that node.js is somehow intrinsically asynchronous. It is not. Node is just V8 javascript with a runtime environment wrapped around it. The runtime environment happens to include an event loop. You have to participate in, and work with the event loop if you want to achieve the illusion of asynchronous behavior. I say "illusion" because the code you write is always going to block, unless you're making an asynchronous IO call to the OS for files or sockets or something. It's up to you to yield your long running processes back to the main event loop.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.