简体   繁体   English

Javascript,简单的回调示例未按预期工作

[英]Javascript, simple callback example not working as expected

First, thanks alot for anybody who will have a look at my question. 首先,非常感谢任何愿意看我问题的人。 It is totally basic but I just don`t get it. 这完全是基础,但是我不明白。 I have looked through all tutorials, but asynchronous callbacks drive me crazy. 我浏览了所有教程,但是异步回调使我发疯。 Thank you so much for helping out, greetings from Germany :) 非常感谢您的帮助,德国的问候:)

If somebody could tell me why below code does not log into the console as expected. 如果有人可以告诉我为什么下面的代码未按预期登录控制台。 Expected means, callback is called after the Timeout function has completed. 预期的方式是,在超时功能完成后调用回调。 Instead, my console logs the callback first? 相反,我的控制台首先记录了回调? What am I still getting wrong here? 我在这里还是怎么了?

function doHomework(subject, callback) {
  setTimeout(function () {
   console.log(`Starting my ${subject} homework.`);
  }, 10);
  callback();
}

doHomework('math', function() {
  console.log('Finished my homework');
});

You need to put the call of a callback function inside your setTimeout 您需要将回调函数的调用放入setTimeout

function doHomework(subject, callback) {
  setTimeout(function () {
   console.log(`Starting my ${subject} homework.`);
   callback();
  }, 10);
}

The problem is that you execute the callback outside of your setTimeout function. 问题是您在setTimeout函数之外执行了回调。 Javascript executes code asynchronously, meaning that it does not wait until the previous code is "finished" before it continues to the next line. Javascript异步执行代码,这意味着它不会等到前一个代码“完成”后才继续下一行。

Hence, when you call doHomework , it will start the timer, and immediately continue to the next line of code, which is the callback. 因此,当您调用doHomework ,它将启动计时器,并立即继续执行下一行代码,即回调。 Then, when the 10ms is over, the code inside the timeout is executed. 然后,当10ms结束时,将执行超时内的代码。 In order to get the desired result, you will have to place the callback execution inside the setTimeout function, like so: 为了获得所需的结果,您必须将回调执行置于setTimeout函数中,如下所示:

function doHomework(subject, callback) {
   setTimeout(function () {
      console.log(`Starting my ${subject} homework.`);
      callback();
   }, 10);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM