How does the JavaScript callback function achieve non-blocking?

the code is as follows:

function Breakfast() {
  var str = "breakfast";
  console.log("Having breakfast");
  // 
  eat(str, function() {
    console.log("Finished ! Time to go to work!" + str);
  });
}


function Lunch() {
  var str = "lunch";
  console.log("Having Lunch");
  // 
  eat(str, function() {
    console.log("Finished ! Time to go to work!" + str);
  });
}

function eat(str, callback) {
  (function() {
    var start = new Date().getTime();
    // 
    while ((new Date().getTime() - start) < 2000) {}
  }());
  // 2
  callback(str);
}


Breakfast();
Lunch();
  • run result:
    Having breakfast
    Finished! Time to go to workstations breakfast
    Having Lunch
    Finished! Time to go to workstations

question: I used a while loop in the eat function and told him to wait two seconds before continuing to execute the callback function. If it is non-blocking, it should not wait but directly output the next segment of Having Lunch, right? So according to the callback function, the result should be
Having breakfast
Having Lunch
Finished! Time to go to workplaces breakfast
Finished! Time to go to workflows
really doesn"t understand how JS callback functions and non-blocking are implemented. If you want to achieve the above output, how should the code be changed? can it be done?

Mar.16,2021

you are mistaken about several things. Callbacks have nothing to do with asynchrony, and asynchrony has nothing to do with blocking and non-blocking.

// 
function async (callback){
    callback()
}
// 
function sync (callback) {
    setTimeout(callback, 500)
}
// 
function noBlock () {
    //  
    // 
    // thread.run()
    // 
    // 
    return 'doing'
}
 js 

node underlying non-blocking is implemented using thread pool (dependent on the system, whether windows or * nix platform). It's like throwing your while loop to another thread for execution, without blocking the current thread's js execution.

Menu