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?