简体   繁体   中英

How does the callback function work with the set timeout function?

module.exports = (x, y , calllback) => {
    if (x <= 0 || y <= 0) {
        setTimeout(() => callback(new Error("Rectangle dimension should be greater than zero"), null), 
            2000);
    }
    else {
        setTimeout(() =>
            calllback(null, {
                perimeter: () => 2 * (x + y), 
                area: () => x * y
            }), 
            2000);
    }
}

My question is: Why do I have to do () => before the callback function as setTimeout takes a function as an input, so why can't I directly do setTimeout(callback(...), 2000). Maybe I lack the understanding of this callback functions to some extent so it would be great if someone could help me!

I'm thankful for every comment.

You need to pass a function into setTimeout, so for some cases you could do this:

setTimeout(callback, 2000);

However, in doing this you give up any control over what values get passed into the callback. So this will only work if the callback doesn't need any data. If it does, you'll need another approach.

Doing the following is not an option:

setTimeout(callback(null, {
  perimeter: () => 2 * (x + y), 
  area: () => x * y
}), 2000);

The reason it's not an option is that this code doesn't pass a function into setTimeout. Instead, it calls the callback immediately and then passes its return value into setTimeout.

So instead, the way to do it is the way in the code snippet you showed: Create a new function, and that function's body does a call to callback and passes in the appropriate values. We pass this new function to setTimeout, then 2 seconds later it gets called, and it turns around and calls the callback.


There is actually one other option, though this is specific to setTimeout and won't be available for many other things that use callbacks. setTimeout allows you to pass additional parameters to setTimeout, and those will then be passed to the callback for you:

setTimeout(
  callback,
  2000,
  null,
  {
    perimeter: () => 2 * (x + y), 
    area: () => x * y
  }
)

You should be able to send a callback to the setTimeout function.

setTimeout(callback, 2000)

but you can't invoke the function like this

setTimeout(callback(), 2000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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