【问题标题】:Why is the callback function not working?为什么回调函数不起作用?
【发布时间】:2021-09-03 23:23:51
【问题描述】:

let fn_one = () => {
  setTimeout(function() {
    console.log("This is shashank");
  }, 5000)

}
let fn_two = (name, callback) => {
  setTimeout(function() {
    console.log("Hi!, " + name);
    callback();
  }, 1000)
}

fn_two("there", fn_one)

这里,fn_two 被调用并在一秒后执行,然而,它有一个回调函数被设置为fn_one()。所以它应该在执行fn_two函数后立即调用回调函数,对吧?为什么在调用 fn_two 后需要 5 秒?为什么它不能在后台运行?

任何人都可以向我解释为什么函数 fn_one 需要 5 秒,即使我已将其调用为回调函数?

【问题讨论】:

  • 因为fn_one使用setTimeout(..., 5000)在5秒后安排console.log()
  • fn_one 会立即被callback() 调用。如果你把console.log('fn_one called'); 放在 fn_one 的 setTimeout 之前,你应该会看到这个。

标签: javascript html asynchronous callback asynccallback


【解决方案1】:

fn_one函数里面有一个5秒的setTimeout,不管你在哪里调用这个函数,里面都有一个setTimeout函数,只有到了总时间之后才会执行setTimeout里面的代码。

要具有立即返回的功能,您需要删除 setTimeout:

let fn_one = () => {
  // setTimeout removed, it will run as soon as it is called.
  console.log("This is shashank");
}
let fn_two = (name, callback) => {
  setTimeout(function() {
    console.log("Hi!, " + name);
    callback();
  }, 1000)
}

fn_two("there", fn_one)

【讨论】:

  • 那么回调函数有什么用呢,为什么不在后台运行呢?
  • 也许你对某些事情感到困惑,阅读回调函数here
猜你喜欢
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
  • 2017-09-23
  • 1970-01-01
相关资源
最近更新 更多