Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Callback after calling function

Ok so lets say I have this function:

function a(message) {
alert(message);
}

And I want to have a callback after the alert window is shown. Something like this:

a("Hi.", function() {});

I'm not sure how to have a callback inside of the function I call like that.

(I'm just using the alert window as an example)

Thanks!

like image 967
ConnorLaCombe Avatar asked Jan 15 '11 15:01

ConnorLaCombe


2 Answers

There's no special syntax for callbacks, just pass the callback function and call it inside your function.

function a(message, cb) {
    console.log(message); // log to the console of recent Browsers
    cb();
}

a("Hi.", function() {
    console.log("After hi...");
});

Output:

Hi.
After hi...
like image 127
Ivo Wetzel Avatar answered Oct 25 '22 15:10

Ivo Wetzel


You can add a if statement to check whether you add a callback function or not. So you can use the function also without a callback.

function a(message, cb) {
    alert(message);
    if (typeof cb === "function") {
        cb();
    }
}
like image 29
Simon Avatar answered Oct 25 '22 16:10

Simon