Blocking vs non-blocking

A blocking operation:


console.log('Hello ' + write('Dribbit', 1000));

function write(text, delay) {
    var start = new Date().getTime();
    while (new Date().getTime() - start < delay) {
        // Waiting...
    }
    return text;
}

console.log('End log');

In this example I use a function write, which uses a delay. When the delay is finished, the function returns a string. As you can see when running this function, the application doesn't execute any code untill the write function has ended. This is synchronous programming, all functions are staying in a queue waiting for the others to finish. As Node is single threaded, the complete application waits for the write function to finish. 

A non blocking operation:


setTimeout(function() {
    console.log('Dribbit');
}, 1000);

console.log('Hello ');

console.log('End log');

By changing the synchronous way into an asynchrounous way, the application doesn't wait. The setTimeout function has an anonymous function as a callback funtion. This callback function returns the result to the application without blocking the application.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.