代码如下: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();运行结果:Having breakfastFinished ! Time to go to work!breakfastHaving LunchFinished ! Time to go to work!lunch问题:我在eat函数中用了一个while循环,让他等待两秒再继续执行回调函数,如果是非阻塞的话,应该就不会等待而是直接输出下一段的Having Lunch才对吧?? 所以按照回调函数非阻塞,结果应该是:Having breakfastHaving LunchFinished ! Time to go to work!breakfastFinished ! Time to go to work!lunch真的没弄明白JS回调函数和非阻塞是怎么实现的。如果要做到上述的输出结果,代码应该怎么改,能做到吗?
添加回答
举报
0/150
提交
取消