Callback function is not working in javascript - javascript

I have read a few articles regarding callback function. I understand how they presented like add a + b then give callback function. But I am doing same. I first declared the function then call it again I call the callback function, why it is not working in my case?
function me(callback){
console.log("1")
}
me(function(){
console.log(2)
})
I am expecting console.log 1 then console.log 2. I am getting only console.log 1

you are calling the callback function, it won't trigger automatically, that approach is so you can notify something using that callback function when your function ended something.
function me(callback) {
console.log("1")
// your process ended, lets notify
callback();
}
me(function() {
console.log(2)
})

You have to actually call the callback function inside the function it is passed to as argument:
function me(callback){
console.log(1)
callback();
}
me(function(){
console.log(2);
})

Related

Problem in my custom setInterval() function in JavaScript

Here I made a custom setInterval function but it is not working as desired.
function interval(func,ti,f){
if(f==0||f==undefined){
try{ //calls the function provided as argument.
func.call();
}
catch(err){ //if error occurs
alert('error occured!'); //edited
throw new Error("error occured!!");//edited
}
setTimeout(interval(func,ti,f),ti);
}
}
The main idea behind this is that the user calls the function somewhat like this:
interval(()=>{
console.log('hello world');
},10000);
Since I'm not passing the value of f so it is undefined
so it satisfies and enters the if statement. Now when try{} calls the function, it executes. The problem is that I am calling the SetInterval function by passing arguments as the function interval() and ti which is the time in milliseconds.
So it should call the function interval() after time ti but it is not doing so.
setTimeout requires a function, you are passing the value of a function call.
Change
setTimeout(interval(func,ti,f),ti);
to
setTimeout(() => interval(func,ti,f),ti);

Usage of Javascript callback function

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);
}

setTimeout nuances in Node.js

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");
};
}

Store jQuery scripts in JS Variable

I have a function with a variable called callback
function test(callback){
// Some code
callback;
}
When I call this function I used to insert a one liner into callback
eg. test($('#elem').hide());
Now I want to put multiple lines in here as the callback. I tried this but it does not appear to work.
var resetc = function(){
$('.access').removeClass('viz');
window.setTimeout(function(){
$('.access').find('.input.wheel').removeClass('viz');
$('.access').find('input').removeAttr('disabled');
},1000);
}
test(resetc);
As you are passing the function reference. You can use the callback variable to execute the function which it is referring. like
function test(callback) {
// Some code
callback();
}
You statement test($('#elem').hide()); is having no effect as you are passing the output of $('#elem').hide() to your method test and statement callback; actually is not performing anything.
You need to change your function call for test($('#elem').hide()); with
test(function() {
$('#elem').hide();
});
Your initial code doesn't do what you think. To call a callback, you need to put () after it:
function test(callback) {
// some code
callback();
}
If you fix that, test(resetc); will do what you want.
The reason you didn't notice this in your first test is because when you write
test($('#elem').hide());
you're executing $('#elem').hide() before calling test, it's not being done when test runs the callback. You need to pass a function to defer the execution until the callback is called:
test(function() {
$('#elem').hide();
});

javascript callback question

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.

Categories