I have some really hard times understanding JS callbacks. From what I understand is that JS callback is a function that takes the argument of another function. So let's say I have a function called myFunction and passes mySecond to it, will it exicute myFunction before mySecond?
function myFunction(){
alert("hello");
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
if you want myFunction before mySecond. The code is below.
function myFunction(func){
alert("hello");
func();
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
Hello, if you want myFunction after mySecond. The code is below.
function myFunction(func){
func();
alert("hello");
}
function mySecond(){
alert("world");}
}
myFunction(mySecond);
a JS callback is a function that takes the argument of another function
This "understanding" is confused and has it backwards:
a JS callback is a function provided as an argument to another function, to be called back after the called function has done something.
A classic example or callback function is provided by the syntax of setTimeout:
setTimeout( callback, 1000);
Here callback (a function) is called back (by setTimeout) after a second has elapsed.
Related
//The anonymous function is not being executed there in the parameter.
//The item is a callback function
$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});
If the anonymous function is not being executed in the parameters of the main function, then how do you execute the anonymous function inside the body of the main function?
Something like this:
function myFunction(function(){ /*code inside anon function */ }){ /*Code insider main function */}
/*Calling the main function */
myFunction();
when does anoymous function get executed?
From your edit, it looks like you have the function declaration and the function callback mixed up.
If a function takes another function as a parameter it will look something like:
// myFunction accepts a function as a parameter
function myFunction(fn){
//call the passed in function
fn() // fn is the function you passed in
}
// Calling the main function and pass in function
myFunction(function(){
console.log("hello")
}
);
So in your original example:
$("#btn_1").click(function() {
alert("Btn 1 Clicked");
});
click() is defined to accept a function, which you passed in. It is analogous to myFunction above except the browser waits to get a click before it calls the function you passed in.
So in answer to your original question:
then how do you execute the anonymous function inside the body of the main function?
The answer is, in the case of event handlers like click() you don't, the browser does.
I think this is so basic so people maybe minus votes on this document, but even so this is so confused me about callback function in JavaScript.
function doSomething(callback){
setTimeout(hello,5000);
callback();
}
function hi(){
console.log("hi");
}
function hello(){
console.log("hello");
}
doSomething(hi);
/* result */
// hi
// (after 5 seconds) hello
I want to use callback function as a handle function's execute order, so I decided use callback pattern. In above code, I think after 5 seconds, the callback function should be executed, but why callback ignore before function and was ran first? Could you tell me a some hint.
Thanks.
In your code callback() was executing after the execution of the line setTimeout() but the callback of setTimeout will trigger after 5000ms, that is the expected behaviour. So if you want callback() to exeute after hello() do:
function doSomething(callback){
setTimeout(function(){
hello();
callback();
},5000);
}
I'm trying to understand how the callback function works inside the setTimeout function. I'm aware the format is: setTimeout(callback, delay) I wrote a little test script to explore this.
test1.js
console.log("Hello")
setTimeout(function () { console.log("Goodbye!") }, 5000)
console.log("Non-blocking")
This works as expected, printing Hello <CRLF> Non-blocking and then 5 seconds later, prints Goodbye!
I then wanted to bring the function outside of the setTimeout like this:
console.log("Hello")
setTimeout(goodbye(), 5000)
console.log("Non-blocking")
function goodbye () {
console.log("Goodbye")
}
but it doesn't work and there isn't a 5 second delay between Non-blocking and Goodbye!, they print straight after each other.
It works if I remove the brackets from the function call in the timeout, like this:
setTimeout(goodbye, 5000)
but this doesn't make sense to me because that's not how you call a function. Futhermore, how would you pass arguments to the function if it looked like this?!
var name = "Adam"
console.log("Hello")
setTimeout(goodbye(name), 5000)
console.log("Non-blocking")
function goodbye (name) {
console.log("Goodbye "+name)
}
My question is really, why doesn't it work when there are parameters in the function, despite the fact the setTimeout is being provided with a valid function with the correct syntax?
By putting the parentheses after your function name, you are effectively calling it, and not passing the function as a callback.
To provide parameters to the function you are calling:
You can pass an anon function. setTimeout(function(){goodbye(name)}, 5000);
Or, you can pass the arguments as a third parameter. setTimeout(goodbye, 5000, name);
Look at this question: How can I pass a parameter to a setTimeout() callback?
No matter where you place it, goodbye(name) executes the function immediately. So you should instead pass the function itself to setTimeout(): setTimeout(goodbye, 5000, name).
When you use it like this:
setTimeout(goodbye(), 5000);
it will first call goodbye to get its return value, then it will call setTimeout using the returned value.
You should call setTimeout with a reference to a callback function, i.e. only specifying the name of the function so that you get its reference instead of calling it:
setTimeout(goodbye, 5000);
To make a function reference when you want to send a parameter to the callback function, you can wrap it in a function expression:
setTimeout(function() { goodbye(name); }, 5000);
You can use parantheses in the call, but then the function should return a function reference to the actual callback function:
setTimeout(createCallback(), 5000);
function createCallback() {
return function() {
console.log("Goodbye");
};
}
$(document).ready(SetupButtonClicks());
function SetupButtonClicks() {
$('#btnJavaPHP').click(DoPHPStuff());
}
function DoPHPStuff() {
//stuff
}
I have this code in my javascript file, when I debug it I see it call SetupButtonClicks() like it should but after that is done it calls DoPHPStuff(). DoPHPStuff() should only be called when btnJavaPHP is clicked. What am I doing wrong?
Change your SetupButtonClicks function:
$('#btnJavaPHP').click(DoHPStuff);
The way you've got it coded, you're telling Javascript to call the function, not to use it as the "click" handler. The parentheses are an operator that causes a function to be called.
Remove the ().
By writing $(document).ready(SetupButtonClicks()), you are calling SetupButtonClicks and passing its return value to ready.
Similarly, by writing $('#btnJavaPHP').click(DoPHPStuff()), you are calling DoPHPStuff (immediately) and passing whatever it returns to click().
You need to pass the functions themselves by writing $(document).ready(SetupButtonClicks) and $('#btnJavaPHP').click(DoPHPStuff).
function DoPHPStuff() {
//stuff
}
function SetupButtonClicks() {
$('#btnJavaPHP').click(DoPHPStuff);
}
$(document).ready(SetupButtonClicks);
With the exception of a function declaration, a pair of parentheses following a function's identifier causes the function to execute. Examples:
// function declaration; function not executed
function SetupButtonClicks() {
}
// function executed
SetupButtonClicks();
// function not executed
SetupButtonClicks;
I have a javascript which I didn't write but I need to use it ..
function function1()
... body..
and at the end
I have this
'callback': 'getListCallback'
}
What does this callback mean and getListCallback = function(obj) is another function, does this mean that results from function1 are returned to function getListCallback?
Tnx
A callback function is a function that is going to be called later, usually when some event occurs. For example, when adding an event listener:
function callback(){
alert("click");
}
document.body.addEventListener("click", callback, true);
In many cases you pass the callback function as an anonymous function:
setTimeout(function(){alert("It's been 1 second");}, 1000);
The code getListCallback = function1(obj); will not call getListCallback with the results of function1(obj). It will store whatever function1(obj) returns into getListCallback. If function1 returns a function, then you can call that function later, like so:
function function1(obj){
return function(){
alert("getListCallback was called. obj = "+obj);
}
}
getListCallback = function1(1);
getListCallback();
Yes, it should mean that
normally a callback function means a function which will call after current function execution finished.
This
getListCallback = function(obj){// do something} is like assigning this "function(obj){//....}" to a variable which can use in any place where you need to use that function.