Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Why doesn't this code block in Node.js?

Why doesn't this code block in Node.js?

Problem

I'm following a Node.js tutorial and in in the section "Blocking and non-blocking" it has this code that's supposed to demonstrate problems with blocking.

function start() {
      console.log("Request handler 'start' was called.");

      function sleep(milliSeconds) {
          var startTime = new Date().getTime();
          while (new Date().getTime() 

index.js

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);

I tried loading http://localhost:8888/start and http://localhost:8888/upload. They're both supposed to take 10 seconds to load because of blocking, but they both load instantly. Why? If I run the sleep() function directly in node.js it blocks, but not in a web browser. Is this no longer a problem that has to be dealt with for some reason?

Problem courtesy of: neuromancer

Solution

Your code looks good, it's possible that your browser is caching the response. Try adding ?random=1234 to the URLs and see if that makes it take longer.

Solution courtesy of: Nathan Friedly

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Why doesn't this code block in Node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×