Related
I'm really new to JS and I'm having a lot of trouble writing/understanding callback functions
Let's say for example, I have the following code, but i dont want
takeNumbersGreaterThan(5);
to be executed until
insertNumbers();
is finished
numbers = [];
greaterThan = [];
insertNumbers();
takeNumbersGreaterThan(5);
insertNumbers(){
for (var i = 0; i<11; i++)
{
numbers.push(i)
}
}
takeNumbersGreaterThan(number){
for (var m = 0; m<numbers.length; m++)
{
if (numbers[m] > number)
{
greaterThan.push(numbers[m])
}
}
}
How do I go about doing that?
The basics (not about callbacks, but about programming languages)
To understand callbacks first you have to understand functions. And to understand functions in javascript you first have to understand variables, values and functions.
Almost all programming language can deal with values. So if you've done any programming you'd have a basic idea of what values are (I'm going to greatly simplify types of values here and refer to both values and references/pointers as "values").
A value is a thing. For example a number or a string. So 22.31 is a value and "Hello Dave" is a value.
Most languages also have the concept of variables (not all do though). A variable is a "name" we give to values to make it easier to process values. For example, in the following, x is a variable:
var x = 12;
.. and it's value is 12.
What do variables allow us to do? It allows us to substitute a value for a name in our calculations. Just like math. For example, if x is 12 and we know we can add 1 to 12 we can also do:
x + 1
Functions are values
In javascript functions are values. For example, in the following we assign a function to a variable:
function a () {return "Hello"}
var y = a;
Since what variables do is to allow you to substitute a name for a value then if you can call the function a using the syntax a() it means you can also do this with the variable y:
y(); // returns "Hello"
Callbacks
If functions are values it also means that you can pass functions as arguments to other functions. For example, the following is how you'd normally call a function in another function:
function a () {return "Hello"}
function b () {return a() + " World"}
b(); // returns "Hello World"
If you can pass functions as a variable, it means you can do something like this:
function a () {return "Hello"}
function b () {return "Bye"}
function c (functionVariable) {return functionVariable() + " World"}
c(a); // returns "Hello World"
c(b); // returns "Bye World"
As you can see. Callbacks are not special at all. They're just the result of the fact that in javascript functions obey the same rules as other values like numbers, arrays and strings.
Callbacks does not mean asynchronous
As you can see from the example above, both calls to the function c return a value. Thus the function c is not asynchronous even though it accepts a callback. So callbacks can be used for both synchronous and asynchronous code.
A good example of a synchronous callback is the Array.sort() method. It sorts an array but accepts an optional callback for you to define how to sort (alphabetically, numerically, by last name etc.).
Why asynchronous code need callbacks
For now forget about ajax or networking code. Let's instead look at a scenario that makes it even more obvious why callbacks are used by asynchronous code.
Say for example you have a button. Now, when the user click this button you want something to happen. How do you do that?
The first thing most people do is probably something like this:
while (1) {
if (button.isClicked) {
doSomething();
}
}
OK. So that's an infinite loop that only checks if the button is clicked and nothing else. Then how do you expect the browser to update the UI and track the mouse? This leads us to the next thing people try to do:
while (1) {
if (button.isClicked) {
doSomething();
}
else {
updateUI();
}
}
OK. Great. But two problems. First, if someone were to write a library like Google Charts or jQuery or anything to do with the UI they either will write their own while(1)... loop or you must manually copy/paste their function into your while loop. This does not scale. Second and more importantly, this is inefficient. That while loop will use 100% CPU time checking a button. Wouldn't it be nicer if the browser can tell us when the button is clicked.
Fortunately in javascript functions are just values. You can pass a function to the browser and tell it to execute your function when someone clicks a button:
button.addEventListener('click', doSomething);
Note: Notice the difference between treating a function as a variable and calling a function. If you want to treat a function as a variable just use the name. If you want to call a function use braces like doSomething().
Why everyone insist on writing asynchronous functions
There are two reasons why everyone seem to insist on making asynchronous APIs, especially in languages like javascript.
First, the low-level file and network I/O are async. This means that if you want to talk to a database or a server or read a file you need to implement it as asynchronous. Also, javascript is single threaded. So if you use the synchronous versions of I/O functions you will freeze everything else.
Second, it turns out that in a lot of cases (but certainly not in all) asynchronous, single-threaded programming is as fast as or sometimes even faster than synchronous multi-threaded programming.
Combined, the two reasons above creates social pressure in the js community to ensure that all I/O code are asynchronous in order to maintain the speed advantage and not block other people's code.
If I understand correctly, you want to know more about callbacks and you want to use them. Let me try too help you using your code.
If you want to execute takeNumbersGreaterThan(5); right after insertNumbers(); using callback function, you could do something like this:
numbers = [];
greaterThan = [];
insertNumbers(takeNumbersGreaterThan, 5);
function insertNumbers(callbackFunction, callbackFunctionParam){
for (var i = 0; i<11; i++)
{
numbers.push(i)
}
callbackFunction(callbackFunctionParam);
}
function takeNumbersGreaterThan(number){
for (var m = 0; m<numbers.length; m++)
{
if (numbers[m] > number)
{
greaterThan.push(numbers[m])
}
}
}
but this is just a simple example of how you can call a callback function after some computation. This code could be improved. The point is, you can pass your callback function as parameter on your function and then later execute this callback function.
You are already there. Your code is almost completely correct.
You was just missing function keywork declaration.
The script below, shows you how to run takeNumbersGreaterThan after insertNumbers. In my sample I also changed the function sign in order to pass array as parameters and avoid some of one common "mistakes" known as closures.
var numbers = [];
var greaterThan = [];
var insertNumbers = function(numbers) {
for (var i = 0; i<11; i++)
numbers.push(i)
}
var takeNumbersGreaterThan = function(number, numbers, greaterThan){
for (var m = 0; m<numbers.length; m++) {
if (numbers[m] > number)
greaterThan.push(numbers[m]);
}
}
// run insert numbers
insertNumbers(numbers);
// run take numbers greater than
takeNumbersGreaterThan(5, numbers, greaterThan);
// log
document.write(greaterThan);
Your code dosen't use any asyncronous calls so you wouldent need to use any callbacks to handle the execution. But if you would like to know how to do it, this would be the way.
numbers = [];
greaterThan = [];
function insertNumbers(callback){
for (var i = 0; i<11; i++)
{
numbers.push(i)
}
callback(); // now execute the callback funtion
}
function takeNumbersGreaterThan(number){
for (var m = 0; m<numbers.length; m++)
{
if (numbers[m] > number)
{
greaterThan.push(numbers[m]);
}
}
console.log(greaterThan);
}
insertNumbers(function() { // here we send a functions as argument to insertNumbers which will execute when callback() is called
takeNumbersGreaterThan(5);
});
insertNumbers takes a argument called "callback". When insertNumbers is finished we simply run callback(). In the initial call to insertNumber we pass a function as argument which will be executed as soon as insertNumers finished (or callback() is called).
Code (for the most part) is executed sequentially. In the code you've provided, the computer runs though the code in the order you've provided it. First it creates a new array object and sets it to the numbers variable, then it creates a new array object and sets it to the greaterThan variable.
Then, it runs the insertNumbers function. Now what the computer does is jump to the code that you've defined in insertNumbers and executes all that code. Then, after it finishes with that, it'll return to executing the initial thread of code it was on which is back at line 4. So now it'll jump to the takeNumbersGreaterThan code. So functionally, you don't need any callbacks since your code doesn't do anything that takes an arbitrary amount of time.
That being explained, you see that takeNumbersGreaterThan doesn't get executed until after insertNumbers is executed.
The only time code isn't executed sequentially is when you start doing multi core/threaded code.
Callbacks are used when something takes an arbitrary amount of time like when you are reading data from a disk or are requesting data from the network.
Callbacks can exist, because functions defined in javascript (and many other langauges) exist as objects in the code. If you don't put the parentheses after a function name, you're actually referencing the function object just like any other variable. So you can pass that function object around in your code and to other bits of code. That is what is happening in this example.
setTimeout(myCallback, 5000)
function myCallback(){
console.log("5 seconds have passed");
}
So, as you can see, I can take my function myCallback and give it to another function, in this instance setTimeout, to use after the other function has completed a task.
I know there is an Answer for this But!! All The Answers covered with only one setTimeout in the loop this Question Looks relevant to me How do I add a delay in a JavaScript loop?
But in my Scenario I Have two setTimeout in the Script, How can this be implemented correctly with timing !! The Program works correctly but the timing what I want is not correct !!!
function clickDate(i)
{
setTimeout((function(){
alert("4");
})(),2000);
}
function clickButton(i)
{
setTimeout((function(){
alert("5");
})(),4000);
}
function doEverything(i)
{
clickDate(i);
clickButton(i);
}
for(var i = 0; i < 4; i++)
{
doEverything(i);
}
You're immediately calling the function when you pass it to setTImeout. Remove the extra parenthesis.
function clickDate(i)
{
setTimeout(function(){
alert("4");
},2000);
}
function clickButton(i)
{
setTimeout(function(){
alert("5");
},4000);
}
function doEverything(i)
{
clickDate(i);
clickButton(i);
}
for(var i = 0; i < 4; i++)
{
doEverything(i);
}
EDIT
It's a little unclear what exactly it is you want your code to do seeing as you're passing i into your function I assume you want to use it somehow. Currently you're creating timeouts that will all launch at once. You'll need to stagger the delay times if you want them to launch in sequence. The code below logs a "4" every 2 seconds and a "5" every "4" seconds by multiplying the delay time by i+1.
// Currently this code displays a 4 every 2 seconds and a 5 every 4 seconds
function clickDate(i)
{
setTimeout(function(){
console.log("4");
},2000 * (i+1));
}
function clickButton(i)
{
setTimeout(function(){
console.log("5");
},4000 * (i+1));
}
function doEverything(i)
{
clickDate(i);
clickButton(i);
}
for(var i = 0; i < 4; i++)
{
doEverything(i);
}
Hello I think you havent read documentation about javascript.
It's asynchronous and it will not wait for the event and continue the process. I will give the answer but I highly recommend to read about Javascript it's good for you only here you will get timing problem because your both the function will be called at the same time. Let me give you the example.
function clickDate(i,callback)
{
setTimeout(function(){
alert("4");
callback();//this will call anonymous function in doEverything
},2000);
}
function clickButton(i)
{
setTimeout(function(){
alert("5");
},4000);
}
function doEverything(i)
{
console.log("In loop index is " , i);
clickDate(i,function(){
clickButton(i);
});
//look closely here I have passed the function in changeData and will call that funtion from clickDate
console.log("In loop terminating index is " , i);
}
for(var i = 0; i < 4; i++)
{
doEverything(i);
}
So here console log will make you clear about asynchronous
functionality. You will see that for loop terminates as it continues
it's work and easily completed in 2 seconds so before your first alert
for loop will complete it's iteration.
Hopefully this will help.
you are calling the callback immediately by adding () to the end of function .
you need to pass the callback with timeout and it will be call for you
setTimeout(function(){
alert('hello');
} , 3000);
function functionName() {
setTimeout(function(){ //Your Code }, 3000);
}
Try this one.
Your approach to mocking asynchronous behavior in JavaScript with setTimeout is a relatively common practice. However, providing each function with its own invocation of setTimeout is an anti-pattern that is working against you simply due to the asynchronous nature of JavaScript itself. setTimeout may seem like it's forcing JS to behave in a synchronous way, thus producing the 4 4 4 4 then 5 5 you are seeing on alert with iteration of the for loop. In reality, JS is still behaving asynchronously, but because you've invoked multiple setTimeout instances with callbacks that are defined as anonymous functions and scoped within their own respective function as an enclosure; you are encapsulating control of JS async behavior away from yourself which is forcing the setTimeout's to run in a strictly synchronous manner.
As an alternative approach to dealing with callback's when using setTimeout, first create a method that provides the timing delay you want to occur. Example:
// timer gives us an empty named "placeholder" we can use later
// to reference the setTimeout instance. This is important because
// remember, JS is async. As such, setTimeout can still have methods
// conditionally set to work against it.
let timer
// "delayHandler", defined below, is a function expression which when
// invoked, sets the setTimeout function to the empty "timer" variable
// we defined previously. Setting the callback function as the function
// expression used to encapsulate setTimeout provides extendable control
// for us later on however we may need it. The "n" argument isn't necessary,
// but does provide a nice way in which to set the delay time programmatically
// rather than hard-coding the delay in ms directly in the setTimeout function
// itself.
const delayHandler = n => timer = setTimeout(delayHandler, n)
Then, define the methods intended as handlers for events. As a side-note, to help keep your JS code from getting messy quickly, wrap your event handler methods within one primary parent function. One (old school) way to do this would be to utilize the JS Revealing Module Pattern. Example:
const ParentFunc = step => {
// "Private" function expression for click button event handler.
// Takes only one argument, "step", a.k.a the index
// value provided later in our for loop. Since we want "clickButton"
// to act as the callback to "clickDate", we add the "delayHandler"
// method we created previously in this function expression.
// Doing so ensures that during the for loop, "clickDate" is invoked
// when after, internally, the "clickButton" method is fired as a
// callback. This process of "Bubbling" up from our callback to the parent
// function ensures the desired timing invocation of our "delayHandler"
// method. It's important to note that even though we are getting lost
// in a bit of "callback hell" here, because we globally referenced
// "delayHandler" to the empty "timer" variable we still have control
// over its conditional async behavior.
const clickButton = step => {
console.log(step)
delayHandler(8000)
}
// "Private" function expression for click date event handler
// that takes two arguments. The first is "step", a.k.a the index
// value provided later in our for loop. The second is "cb", a.k.a
// a reference to the function expression we defined above as the
// button click event handler method.
const clickDate = (step, cb) => {
console.log(step)
cb(delayHandler(8000))
}
// Return our "Private" methods as the default public return value
// of "ParentFunc"
return clickDate(step, clickButton(step))
}
Finally, create the for loop. Within the loop, invoke "ParentFunc". This starts the setTimeout instance and will run each time the loop is run. Example:
for(let i = 0; i < 4; i++) {
// Within the for loop, wrap "ParentFunc" in the conditional logic desired
// to stop the setTimeOut function from running further. i.e. if "i" is
// greater than or equal to 2. The time in ms the setTimeOut was set to run
// for will no longer hold true so long as the conditional we want defined
// ever returns true. To stop the setTimeOut method correctly, use the
// "clearTimeout" method; passing in "timer", a.k.a our variable reference
// to the setTimeOut instance, as the single argument needed to do so.
// Thus utilizing JavaScript's inherit async behavior in a "pseudo"
// synchronous way.
if(i >= 2) clearTimeout(timer)
ParentFunc(i)
}
As a final note, though instantiating setTimeOut is common practice in mocking asynchronous behavior, when dealing with initial invocation/execution and all subsequent lifecycle timing of the methods intended to act as the event handlers, defer to utilizing Promises. Using Promises to resolve your event handlers ensures the timing of method(s) execution is relative to the scenario in which they are invoked and is not restricted to the rigid timing behavior defined in something like the "setTimeOut" approach.
I'm really new to JS and I'm having a lot of trouble writing/understanding callback functions
Let's say for example, I have the following code, but i dont want
takeNumbersGreaterThan(5);
to be executed until
insertNumbers();
is finished
numbers = [];
greaterThan = [];
insertNumbers();
takeNumbersGreaterThan(5);
insertNumbers(){
for (var i = 0; i<11; i++)
{
numbers.push(i)
}
}
takeNumbersGreaterThan(number){
for (var m = 0; m<numbers.length; m++)
{
if (numbers[m] > number)
{
greaterThan.push(numbers[m])
}
}
}
How do I go about doing that?
The basics (not about callbacks, but about programming languages)
To understand callbacks first you have to understand functions. And to understand functions in javascript you first have to understand variables, values and functions.
Almost all programming language can deal with values. So if you've done any programming you'd have a basic idea of what values are (I'm going to greatly simplify types of values here and refer to both values and references/pointers as "values").
A value is a thing. For example a number or a string. So 22.31 is a value and "Hello Dave" is a value.
Most languages also have the concept of variables (not all do though). A variable is a "name" we give to values to make it easier to process values. For example, in the following, x is a variable:
var x = 12;
.. and it's value is 12.
What do variables allow us to do? It allows us to substitute a value for a name in our calculations. Just like math. For example, if x is 12 and we know we can add 1 to 12 we can also do:
x + 1
Functions are values
In javascript functions are values. For example, in the following we assign a function to a variable:
function a () {return "Hello"}
var y = a;
Since what variables do is to allow you to substitute a name for a value then if you can call the function a using the syntax a() it means you can also do this with the variable y:
y(); // returns "Hello"
Callbacks
If functions are values it also means that you can pass functions as arguments to other functions. For example, the following is how you'd normally call a function in another function:
function a () {return "Hello"}
function b () {return a() + " World"}
b(); // returns "Hello World"
If you can pass functions as a variable, it means you can do something like this:
function a () {return "Hello"}
function b () {return "Bye"}
function c (functionVariable) {return functionVariable() + " World"}
c(a); // returns "Hello World"
c(b); // returns "Bye World"
As you can see. Callbacks are not special at all. They're just the result of the fact that in javascript functions obey the same rules as other values like numbers, arrays and strings.
Callbacks does not mean asynchronous
As you can see from the example above, both calls to the function c return a value. Thus the function c is not asynchronous even though it accepts a callback. So callbacks can be used for both synchronous and asynchronous code.
A good example of a synchronous callback is the Array.sort() method. It sorts an array but accepts an optional callback for you to define how to sort (alphabetically, numerically, by last name etc.).
Why asynchronous code need callbacks
For now forget about ajax or networking code. Let's instead look at a scenario that makes it even more obvious why callbacks are used by asynchronous code.
Say for example you have a button. Now, when the user click this button you want something to happen. How do you do that?
The first thing most people do is probably something like this:
while (1) {
if (button.isClicked) {
doSomething();
}
}
OK. So that's an infinite loop that only checks if the button is clicked and nothing else. Then how do you expect the browser to update the UI and track the mouse? This leads us to the next thing people try to do:
while (1) {
if (button.isClicked) {
doSomething();
}
else {
updateUI();
}
}
OK. Great. But two problems. First, if someone were to write a library like Google Charts or jQuery or anything to do with the UI they either will write their own while(1)... loop or you must manually copy/paste their function into your while loop. This does not scale. Second and more importantly, this is inefficient. That while loop will use 100% CPU time checking a button. Wouldn't it be nicer if the browser can tell us when the button is clicked.
Fortunately in javascript functions are just values. You can pass a function to the browser and tell it to execute your function when someone clicks a button:
button.addEventListener('click', doSomething);
Note: Notice the difference between treating a function as a variable and calling a function. If you want to treat a function as a variable just use the name. If you want to call a function use braces like doSomething().
Why everyone insist on writing asynchronous functions
There are two reasons why everyone seem to insist on making asynchronous APIs, especially in languages like javascript.
First, the low-level file and network I/O are async. This means that if you want to talk to a database or a server or read a file you need to implement it as asynchronous. Also, javascript is single threaded. So if you use the synchronous versions of I/O functions you will freeze everything else.
Second, it turns out that in a lot of cases (but certainly not in all) asynchronous, single-threaded programming is as fast as or sometimes even faster than synchronous multi-threaded programming.
Combined, the two reasons above creates social pressure in the js community to ensure that all I/O code are asynchronous in order to maintain the speed advantage and not block other people's code.
If I understand correctly, you want to know more about callbacks and you want to use them. Let me try too help you using your code.
If you want to execute takeNumbersGreaterThan(5); right after insertNumbers(); using callback function, you could do something like this:
numbers = [];
greaterThan = [];
insertNumbers(takeNumbersGreaterThan, 5);
function insertNumbers(callbackFunction, callbackFunctionParam){
for (var i = 0; i<11; i++)
{
numbers.push(i)
}
callbackFunction(callbackFunctionParam);
}
function takeNumbersGreaterThan(number){
for (var m = 0; m<numbers.length; m++)
{
if (numbers[m] > number)
{
greaterThan.push(numbers[m])
}
}
}
but this is just a simple example of how you can call a callback function after some computation. This code could be improved. The point is, you can pass your callback function as parameter on your function and then later execute this callback function.
You are already there. Your code is almost completely correct.
You was just missing function keywork declaration.
The script below, shows you how to run takeNumbersGreaterThan after insertNumbers. In my sample I also changed the function sign in order to pass array as parameters and avoid some of one common "mistakes" known as closures.
var numbers = [];
var greaterThan = [];
var insertNumbers = function(numbers) {
for (var i = 0; i<11; i++)
numbers.push(i)
}
var takeNumbersGreaterThan = function(number, numbers, greaterThan){
for (var m = 0; m<numbers.length; m++) {
if (numbers[m] > number)
greaterThan.push(numbers[m]);
}
}
// run insert numbers
insertNumbers(numbers);
// run take numbers greater than
takeNumbersGreaterThan(5, numbers, greaterThan);
// log
document.write(greaterThan);
Your code dosen't use any asyncronous calls so you wouldent need to use any callbacks to handle the execution. But if you would like to know how to do it, this would be the way.
numbers = [];
greaterThan = [];
function insertNumbers(callback){
for (var i = 0; i<11; i++)
{
numbers.push(i)
}
callback(); // now execute the callback funtion
}
function takeNumbersGreaterThan(number){
for (var m = 0; m<numbers.length; m++)
{
if (numbers[m] > number)
{
greaterThan.push(numbers[m]);
}
}
console.log(greaterThan);
}
insertNumbers(function() { // here we send a functions as argument to insertNumbers which will execute when callback() is called
takeNumbersGreaterThan(5);
});
insertNumbers takes a argument called "callback". When insertNumbers is finished we simply run callback(). In the initial call to insertNumber we pass a function as argument which will be executed as soon as insertNumers finished (or callback() is called).
Code (for the most part) is executed sequentially. In the code you've provided, the computer runs though the code in the order you've provided it. First it creates a new array object and sets it to the numbers variable, then it creates a new array object and sets it to the greaterThan variable.
Then, it runs the insertNumbers function. Now what the computer does is jump to the code that you've defined in insertNumbers and executes all that code. Then, after it finishes with that, it'll return to executing the initial thread of code it was on which is back at line 4. So now it'll jump to the takeNumbersGreaterThan code. So functionally, you don't need any callbacks since your code doesn't do anything that takes an arbitrary amount of time.
That being explained, you see that takeNumbersGreaterThan doesn't get executed until after insertNumbers is executed.
The only time code isn't executed sequentially is when you start doing multi core/threaded code.
Callbacks are used when something takes an arbitrary amount of time like when you are reading data from a disk or are requesting data from the network.
Callbacks can exist, because functions defined in javascript (and many other langauges) exist as objects in the code. If you don't put the parentheses after a function name, you're actually referencing the function object just like any other variable. So you can pass that function object around in your code and to other bits of code. That is what is happening in this example.
setTimeout(myCallback, 5000)
function myCallback(){
console.log("5 seconds have passed");
}
So, as you can see, I can take my function myCallback and give it to another function, in this instance setTimeout, to use after the other function has completed a task.
Just a couple of questions regarding using Nodejs in Web Development.
1) For my Concurrency question, it regards syntax. Is there a difference between:
setInterval(function() {
console.log('Task A');
}, 10);
and
function setInterval() {
console.log('Task A');
}, 10);
Also, i'm a little confused what the '10' means at the end of the method, my guess is the time it takes for the method to complete?
2) Callbacks - Are Callbacks just technically another name in Node for testing code?
3) Is there a method I can use in the Node(CLI) to see all of the methods in a module?
EX:
var fs = require('fs');
Obviously there are tons of methods in the File Systems module, but like the language Ruby, using PRY in the CLI, you can type 'fs.methods', which will display all of the methods. Then using 'cat', you can see the contents of each individual method. Something like this for Node(CLI)?
Thanks for all of the advice/answers!
Cheers,
G
1.
In the first, you pass in an anonymous function which will be invoked at the interval. Here you are using the node.js API setInterval.
In the second example, you are declaring a function called setInterval. Looks like a syntax error is there...
setInterval is a function that takes 2 objects in as parameters. That's it. the first parameter should be a function, and the second parameter should be a the the interval time in milliseconds. All that setInterval does is run the function passed in in the first parameter(a callback) every x milliseconds as specified in the 2nd parameter.
2.
No. Callbacks are functions that can be passed to other functions so that they can be "called-back" later in the code. Callbacks are pervasive in node.js applications and tightly related to it's asynchronous event based architecture. It is one of the most common patterns seen in node.js.
3.
Just look in node.js api docs on their website.
My recommendation to you would be to read about the node.js event loop and asynchronous programming.
First off, you're asking about some pretty fundamental aspects of Javascript so I'd suggest you work though some basic Javascript training because it will be hard to learn node.js if you don't already have a core understanding of the basics of Javascript. In particular callbacks are integral to much of nodejs coding.
Is there a difference between these two?
Yes, the two are completely different. One uses a built-in timer function, the other attempts to declare it's own function that has nothing to do with timers.
Let me explain your two examples:
The built-in setInterval function
setInterval(function() {
console.log('Task A');
}, 10);
Nodejs has a built-in timer function called setInterval. You can find the doc for it here.
You pass this function two arguments. The first argument is a function reference, the second argument is an amount of time in milliseconds. The nodejs timer infrastructure will call the function you passed it every N milliseconds.
It might be slightly easier to understand how setInterval works by seeing it used like this:
function myFunction() {
console.log('Task A');
}
setInterval(myFunction, 10);
This has the same output as your first example, but I think it shows more clearly how setInterval() is a built-in function that takes two arguments, a function and a number.
In your example, instead of the named function you are passing an anonymous function that simply does console.log('Task A'); and that function will be called every 10ms (approximately).
Create Your Own Function
function setInterval() {
console.log('Task A');
}, 10);
This block of code is a Javascript Syntax Error and will not work. It looks like you're attempting to define your own function called setInterval(), but this is not the proper syntax for declaring a function.
You could make it legal syntax like this:
function setInterval() {
console.log('Task A');
}
And, then you would call it like this:
setInterval();
This has nothing to do with the previous example. This just creates a function that runs once each time you call it. If you actually gave it the same name as the global function setInterval(), then your local definition would replace it within the scope it was declared.
Your Other Questions
Also, i'm a little confused what the '10' means at the end of the
method, my guess is the time it takes for the method to complete?
The 10 in the first example is the number of milliseconds for the interval timer. The 10 in the second example does not belong there - it's part of a Javascript syntax error.
Callbacks - Are Callbacks just technically another name in Node for
testing code?
No. A callback is when a function takes an argument that is a function reference (e.g. the name of a function or an anonymous function). When you pass a callback to this function, you can expect that the function will call the callback one or more times at some time in the future. When exactly it is called or how many times it is called depends entirely upon what the function does and how it is written. The term "callback" comes from the notion that this function will be "called back" some time in the future.
Is there a method I can use in the Node(CLI) to see all of the methods
in a module?
I'm not aware of a specific feature in the command line interface that will give you the methods of a module, but you can iterate them yourself or look at them in the debugger.
When you load a module in node with something like:
var fs = require('fs');
The object you get back from the require() function is a Javascript object. All the methods of that module are properties on that object. You can inspect that object in the debugger or with console.log(fs) or by writing code to iterate the properties of that object.
var fs = require('fs');
for (var prop in fs) {
if (fs.hasOwnProperty(prop)) {
console.log(prop);
}
}
I'm doing some testing and optimizing on a JavaScript function I made. I notice that the add-on I'm using in Firefox (FireUnit) gives a return of the number of calls done during the profiling time. Is this the number of http calls made by the script?
Also, can you outline/discuss/grade/explain as to how many calls is considered within a good range? Maybe by giving examples or commonly-used JavaScript functions such as drop-down menus, hide/show images, image slideshow functionality, etc...
Does a call represent any measure of 'work' or merely the iterations performed?
In this context, a call is the amount of times a function has been invoked.
function foo() {
};
foo();
foo();
The function foo has been called/ invoked twice in the above example.
There is no answer for "what is a good range of calls". A function like jQuery will most likely be called a large number of times per page, whereas you would expect a function like init() to be called only once.
A better representation of the efficiency of your functions is their execution time; this records the amount of time taken for the function to execute (almost always recorded in milliseconds). Functions with long execution times could be optimized to lower their execution time and improve the efficiency of your program.
To best spend you time, you could combine the two statistics (call count and execution time), and look at optimizing the functions that are called a large number of times, and have longer execution times.
The number of calls means how many times a given function was run or invoked or executed. There is no good range in the number of calls. This number gives you two most important informations:
First, if some function is called only once and some other function is called 100 times then every optimization in the latter is 100 times more important than in the former. It is often a waste of time to optimize a function called only once, but if a function is called a lot of times then it may be important to see if it is not too slow.
The second thing you can see from the number of function calls is that if some function is called hundreds of times when in fact it always has the same result then it might mean that you are calling it inside a loop when calling it once and storing the value in a variable might be sufficient.
For example this would call the expensiveFunction 1000 times:
for (i = 0; i < 1000; i++) {
array[i] = i + expensiveFunction();
}
While this would call it only once:
value = expensiveFunction();
for (i = 0; i < 1000; i++) {
array[i] = i + value;
}
Seeing that some of your functions was called a lot of times might be a hint that you have some code similar to that example. Of course you can't cache the value every time but sometimes you do and knowing the number of function calls can be useful.