JavaScript: Callback which doesn't stop execution of lines below


Before this question, I already thought that I had mastered JavaScript.. but no, not even close :)

I'm currently programming with require.js and trying to make methods with callbacks (because of async js) but the problem is that code continues execution after my callback(); calls.

See following example:

var Second = function () {
    console.log("Second init");

Second.prototype.load = function (callback) {

    console.log("Second load");

    var timeOut = setTimeout(function () {


        if (true) {
            console.log("Second interval ended.. GOOD");

        console.log("Second interval ended.. NO, YOU SHOULD NOT BE HERE!");

    }, 1000);

var First = function () {

    console.log("First init");
    var second = new Second();

    second.load(function (returned) {
        console.log("Second returned: " + returned);



This will output:

First init
Second init
Second load
Second interval ended.. GOO
Second returned: true
Second interval ended.. NO, YOU SHOULD NOT BE HERE!
Second returned: false

Where obviously two last lines are too much... What I would want't is a proper way to do callback in following scenarion.. I tried:

if (true) {
    console.log("Second interval ended.. GOOD");
    return callback(true);

Which works, and:

if (true) {
    console.log("Second interval ended.. GOOD");
    return function() {

Which works too, but both of them feels like wrong solutions to me.. how to do this correctly?, thanks!

Problem courtesy of: Mauno Vähä


It can be a matter of opinion, but return callback() is typically the standard. You can see it used this way in the Node source. Example from the filesystem module:

fs.fstat(fd, function(er, st) {
  if (er) return callback(er);
  size = st.size;
  if (size === 0) {
    // the kernel lies about many files.
    // Go ahead and try to read some bytes.
    buffers = [];
    return read();

  buffer = new Buffer(size);
Solution courtesy of: hexacyanide


If you don't want code executed after you have called your callback, just don't place any there. If you hadn't placed a console.log statement after your call to the callback function nothing would have happened: your function would simply have returned.

Discussion courtesy of: user1864610

This recipe can be found in it's original form on Stack Over Flow.