javascript - Node.js: How would you recreate the 'setTimeout' function without it blocking the event loop? -
javascript - Node.js: How would you recreate the 'setTimeout' function without it blocking the event loop? -
i've done lot of searching seek , find out how create non-blocking code in node.js. unfortunately, every illustration i've found grounded function that, in end, has built in callback. wanted create own function callback, reason blocks event loop. didn't block event loop:
function foo(response){ settimeout(function(){ response.writehead(200, {"content-type": "text/plain"}); response.write("bar"); response.end(); }, 7000); }
but did :
function foo(response){ function wait(callback, delay){ var starttime = new date().gettime(); while (new date().gettime() < starttime + delay); callback(); } wait(function(){ response.writehead(200, {"content-type": "text/plain"}); response.write("bar"); response.end(); }, 7000); }
what fundamental aspect of non-blocking code missing?
edit:
my goal recreate settimeout more of mental exercise thought i'd seek can understand loop little better. right i'm worried if have rather heavy server side code that's doing raw processing in javascript, won't know how stop halting event loop.
after reading answers , thinking bit further, think more accurate question this: if i'm doing heavy processing on server javascript, how stop interrupting event loop?
it's first time posting on here, didn't know kind of response gonna get. far, awesome. thanks, guys.
edit 2: hey, 1 time again advice. ended trying out process.nexttick raynos suggested... , worked! managed create own non-blocking timer callback. code isn't perfect, curious, how looks:
var timer = {}; function delay(callback, length){ if(!timer.starttime){ timer.starttime = new date().gettime(); timer.callback = callback; timer.length = length; } if(new date().gettime() < timer.starttime + timer.length){ process.nexttick(delay); } else { timer.callback(); timer = {}; } } function list(response){ delay(function(){ console.log("callback"); exec("dir", function (error, stdout, stderr) { response.writehead(200, {"content-type": "text/plain"}); response.write(stdout); response.end(); }); }, 7000); }
not intending utilize code. process of learning how helped me understand key concepts non-blocking.
and of still curious non-blocking, should check out raynos' article.
in order not block event loop code has homecoming event loop , allow go on processing. unless code returns event loop can't dequeue next message , process it. code won't exit given period of time , hence never returns command event loop.
javascript node.js
Comments
Post a Comment