I am new to javascript, I have gone through tutorials about callbacks, but I don't see any that answers this, both method below offers the same results, the only difference I see is callback allows dynamically passing in a callback function.
Are there other advantages, I am missing?
Thank you.
Callback
function logOne(callback) {
setTimeout(() => {
console.log("one");
callback();
}, 1000);
}
function logTwo() {
console.log("two");
}
logOne(logTwo); // one, two
No Callback
function logOne() {
setTimeout(() => {
console.log("one");
logTwo();
}, 1000);
}
function logTwo() {
console.log("two");
}
logOne(); // one, two
Your first example is more flexible: You can use any callback, not just logTwo.
Both have their uses, it depends on whether you need the flexibility or whether logOne should be specifically tied to logTwo.
Callback of function: If you want to do some operation on some event
Like show time on click of a button. Then you override onclick
function for that button. So whenever (independent on time) that
button is clicked, that application internal framework will call
onclick event and your onclick function will be called.
Normal function : Every function is normal function
Calling a function is when you actually do the function.
Passing a function is when function A needs function B in order to
work. So when you call function A, you pass it function B as an
argument. In this case you are not calling function B, instead you are
providing it to function A so that function A can call it.
Your second example create a tight coupling between logOne and logTwo functions. This way you end up with a logOne function that can't be reused since it only works with one exact function.
By passing a callback, you make your function more flexible and generalized. Now it is able to work with a wide range of other functions as long as they have the same "shape" - same number of arguments in a same order.
Related
Sorry for the ambiguous title, I just didn't know what else to put. Im learning JS and in the video the person does this.
When he calls the addListAfterKeyPress method at the bottom, why does the function call work? I thought he would have to put in a argument for the addListAfterKeyPress to take in since it has an event parameter. But in the end the code works perfectly. And also, when can i call a function that takes a parameter without explicitly passing one like how he did it in the picture?
This is a so called callback.
addListAfterKeypress at line 30 is not a call to this function, it is just saying, whenever the event keypress is raised on this input element, call this function.
Who is calling the function is the DOM library, indeed. You just have to pass a pointer to the function to be called.
Even more, the addListAfterKeypress function expects an event parameter, which will be provided to the function by the DOM library.
I think it is a bit more understanding by looking at an annonymous function there.
input.addEventListener('keypress', event => {
// This will be run whenever the input raises an event of type 'keypress'
// Here, the DOM library provides me an event parameter
});
Edit on demand:
Be aware, I am using ES6 just for comfort.
Suppose having this function
const callback = () => {
console.log(`My callback function is being executed`);
};
I will be using setTimeout to mock the HTML events. setTimeout is a function that expects a callback to execute after n milliseconds.The first parameter is the callback itself, the second is the amount of milliseconds, n.
See https://www.w3schools.com/jsref/met_win_settimeout.asp
setTimeout(callback, 500); // After 500ms, function callback will be fired
Here, I am just passing a pointer to the setTimeout function. This pointer must point to a function that will be called by setTimeout.
Let's write our own function that takes a callback as a parameter.
const callback2 = (number) => {
console.log('I received this parameter', number);
};
const callbackWrap = (callback, n) => {
// Here, callback parameter is a function that I can invoke, actually
console.log('The wrapper will execute the function passed as parameter');
callback(n);
};
Now, we can call the wrapper pointing to the new callback (callback2).
callbackWrap(callback2, 3);
callbackWrap(callback2, 4);
Or, we can define our function directly on the parameter list.
That is, we are passing an annonymous function
// p is the parameter of the callback function
callbackWrap(p => {
// Since callbackWrap will call the function parameter
// by passing a single parameter,
// the function I am declaring, expects that parameter
console.log(`Received ${p} inside the annonymous function`);
}, 'Parameter');
So, to summerize a bit, just the same way you can declare a variable (let's say, of type number) and then pass it to a function as a parameter, you can declare a function to pass it the same way.
const normalParameter = 30;
const functionParameter = p => console.log('Another callback', p);
callbackWrap(functionParameter, normalParameter);
// Or maybe passing more complex parameters
const anotherParameter = [1, '2', {3: 4}];
callbackWrap(functionParameter, anotherParameter );
Hope it clarifies a bit.
I am looking at this code: https://reactjs.org/docs/state-and-lifecycle.html
I do not understand why I need to use () => this.tick() instead of just this.tick(). The prior calls a function that uses this.tick(), yet when I change () => this.tick() to this.tick(), the code stops working. this.tick() is no longer being called even though it itself is a function. () => this.tick() seems to be just an unnecessary step and yet it is necessary.
I think I am misunderstanding functions as objects.
Thank you
If you pass () => this.tick() then you are passing a function.
If you pass this.tick() then you are passing the value returned by the function.
setInterval(func, delay[, param1, param2, ...]) expects a function as first parameter.
() => this.tick() is a function that when executed will call this.tick() with the appropriate context. If you didn't want to use arrow syntax, you would need to bind the this context similar to this.tick.bind(this);
The arrow function used there is needed to bind the this context, so that it can use this in it's own function.
If you would have only setTimeout( this.tick, 1000 ), it would rightfully call the function on the class, however, that function wouldn't have a this scope...
...unless you bind the this scope in the constructor, or as part of the setTimeout call itself
To do it in the constructor you would have something like
class Clock extends Component {
constructor() {
super();
this.tick = this.tick.bind(this);
}
// other functions
tick() {
this.setState(/*.. state content ..*/):
}
}
another option would be the
setTimeout( this.tick.bind( this ), 1000 );
but that would do the same as what the arrow function is doing for you anyhow, so why not use the arrow function instead.
Another option would be the experimental class properties where you would still have an arrow function, but as this is not the most optimal solution when it comes to testing, I will not directly discuss that one
Firstly, setInterval takes a function as a parameter. Hence unless this.tick returns a function, passing this.tick() to setInterval is incorrect.
setInterval defers the callback method in the event loop. And hence at the time of its execution, the current reference to this will have been lost, as its scope is within its parent function which would have completed its execution. So this would be pointing to window or undefined ins strict mode.
To make it work, you need to preserve the reference, for which we create a closure by creating a new function () => this.tick. Now the reference will be preserved even after parent funtion completes its execution.
You need to give the function a callback to be invoked. A callback is a function that is to be executed after another function has finished. For example using a setTimeout is a built-in function, you give tick a callback because once setTimeout is finished you would like tick to be invoked.
Hope this helps!
I'm trying to understand JS and I'm really confused by the callback pattern.
function one(){
alert("I'm one!")
}
function total(arg, callback){
setTimeout(function() {alert("I'm "+arg);}, 1000);
callback();
}
total('all', one);
versus
function one(){
alert("I'm one!")
}
function total(arg){
setTimeout(function() {alert("I'm "+arg);}, 1000);
one();
}
total('all');
What is the benefit of passing one() as a parameter vs just calling it from within the function?
If you know that you're always going to call one, there's no need to accept it as an input parameter; you can just go ahead and call it.
The ability to accept callbacks allows you to easily write loosely coupled code.
You are, for instance, passing a callback to setTimeout in your code example. setTimeout knows to wait a given number of milliseconds before a function is called, but it doesn't know which function to call.
Passing in callback functions allows you to dynamically affect the flow of the program. Additionally, you could pass the outcome of total as a parameter to callback, which is often used to enable asynchronous programming.
function one(){
alert("I'm one!")
}
function total(arg, callback){
setTimeout(function() {
if (callback) {
callback();
}
}, 1000);
}
I suspect that your examples are not what was intended to showcase what a callback is. Does this make more sense?
function cb(arg){
alert("I'm "+arg+"!")
}
function total(arg, callback){
setTimeout(callback, 1000, arg);
}
total('one', cb);
Callback argument allows you to define custom interaction. It's commonly used with any asynchronous operation to allow reacting of state change (for example when operation is done, or errored).
One example of that may be an AJAX call (here with jQuery for simpliciy):
var request = $.ajax({
url: "script.php"
});
// this allows you to specify custom action handling
request.done(one);
I'm trying to build an API in JS that will perform some operations and then execute the callback that's registered in AS when it's done. Because it's an API, I am just providing a JS method signature for another developer to call in Flash. Thus, the callback name that's registered in the AS part of the code should be a parameter that's passed in to the JS API in order for JS to communicate back to Flash.
For example:
[AS3 code]
ExternalInterface.addCallback("flashCallbackName", processRequest);
ExternalInterface.call("namespace.jsFnToCall", flashCallbackName);
function processRequest(data:String):void
{
//do stuff
}
[JS code]
var namespace =
{
jsFnToCall: function(callback)
{
//Do stuff in this function and then fire the callback when done.
//getFlashMovie is just a util function that grabs the
//Flash element via the DOM; assume "flash_id"'s a global var
//Below does not work...it's what I'd be ideally be doing some how.
getFlashMovie(flash_id).callback(data);
}
};
Because the definition of the function is in AS, I can't use the window[function name] approach. The only way I can think of is to build the callback in a string and then use the eval() to execute it.
Suggestions? T.I.A.
Well, I can think of one thing I would try, and one thing that would work.
What I would try first.
getFlashMovie(flash_id)['callback'](data);
What would work: Have the callback always be the same, say callback. The first parameter to the callback could be used to determine what actual function to call in flash. For example:
function callback($fn:String, $data:*) {
// either
this[$fn]($data);
// or
switch ($fn) {
case "callback1":
DoSomeCallback($data);
break;
}
Additionally passing the objectID makes it a bit simpler:
ExternalInterface.addCallback("flashCallbackName", processRequest);
ExternalInterface.call("namespace.jsFnToCall", ExternalInterface.objectID, "flashCallbackName");
Then in your JS:
var namespace =
{
jsFnToCall: function(objectID, callback)
{
//Do stuff in this function and then fire the callback when done.
document[objectID][callback](data);
}
};
What is the meaning of callback function in javascript.
JavaScript's "callback" is function object that can be passed to some other function (like a function pointer or a delegate function), and then called when the function completes, or when there is a need to do so. For example, you can have one main function to which you can pass a function that it will call...
Main function can look like this:
function mainFunc(callBack)
{
alert("After you click ok, I'll call your callBack");
//Now lets call the CallBack function
callBack();
}
You will call it like this:
mainFunc(function(){alert("LALALALALALA ITS CALLBACK!");}
Or:
function thisIsCallback()
{
alert("LALALALALALA ITS CALLBACK!");
}
mainFunc(thisIsCallback);
This is extensively used in javascript libraries. For example jQuery's animation() function can be passed a function like this to be called when the animation ends.
Passing callback function to some other function doesn't guarantee that it will be called. Executing a callback call (calBack()) totally depends on that function's implementation.
Even the name "call-back" is self-explanatory... =)
It's just a name for a function that should be called back after something.
It's often used with XMLHttpRequest:
var x = new XMLHttpRequest();
x.onreadystatechange = function(){
if(x.readyState == 4){
callbackfunction(x.responseText);
}
}
x.open('get', 'http://example.com/', true);
x.send(null);
callbackfunction is just a plain function, in this case:
function callbackfunction(text){
alert("I received: " + text);
}
Besides just being a function, a callback function is an enabler for asynchronous application design.
Instead of calling a function and waiting for the return value(s), potentially locking up the thread or the entire PC or UI on single threaded systems while you wait, with the async pattern you call a function, it returns before finishing, and then you can exit your code (return back to the calling OS, idle state, run loop, whatever...). Then later, the OS or asynchronous function calls your code back. The code you want it to call back is usually encapsulated in something called a "callback function". There are other uses, but this is a common one in OOP UI frameworks.
With the latest iOS 4.x, you can also use nameless "blocks" for the callback. But languages that don't have blocks (or anon closures under another name) use functions for function callbacks.
You can simply use the below statement onClick event of back button:
OnClick="javascript:history.go(-1)"
it will work to take you back to your previous page which you had visited recently.