06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Server-Side <strong>JavaScript</strong><br />

This fragment uses two important concepts. First, we are using named functions and<br />

using them as callbacks. Second, we are not nesting these asynchronous functions. If<br />

you are accessing closure variables within the inner functions, the preceding would<br />

be a bit different implementation. In such cases, using inline anonymous functions is<br />

even more preferable.<br />

Callbacks are most frequently used in Node. They are usually preferred to define<br />

logic for one-off responses. When you need to respond to repeating events, Node<br />

provides another mechanism for this. Before going further, we need to understand<br />

the function of timers and events in Node.<br />

Timers<br />

Timers are used to schedule the execution of a particular callback after a specific<br />

delay. There are two primary methods to set up such delayed execution: setTimeout<br />

and setInterval. The setTimeout() function is used to schedule the execution of<br />

a specific callback after a delay, while setInterval is used to schedule the repeated<br />

execution of a callback. The setTimeout function is useful to perform tasks that need<br />

to be scheduled such as housekeeping. Consider the following example:<br />

setTimeout(function() {<br />

console.log("This is just one time delay");<br />

},1000);<br />

var count=0;<br />

var t = setInterval(function() {<br />

count++;<br />

console.log(count);<br />

if (count> 5){<br />

clearInteval(t);<br />

}<br />

}, 2000 );<br />

First, we are using setTimeout() to execute a callback (the anonymous function)<br />

after a delay of 1,000 ms. This is just a one-time schedule for this callback. We<br />

scheduled the repeated execution of the callback using setInterval(). Note that we<br />

are assigning the value returned by setInterval() in a variable t—we can use this<br />

reference in clearInterval() to clear this schedule.<br />

[ 210 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!