Given a function fn, an array or arguments args, and a timeout t in milliseconds, return a cancel function cancelFn. After a delay of t, fn should be called with args passed as parameters unless cancelFn was called first. In that case, fn should never be called. Example 1: Input: fn = (x) => x * 5, args = [2], t = 20, cancelTime = 50 Output: [{"time": 20, "returned": 10}] Explanation: const cancel = cancellable(fn, [2], 20); // fn(2) called at t=20ms setTimeout(cancel, 50); the cancelTime (50ms) is after the delay time (20ms), so fn(2) should be called at t=20ms. The value returned from fn is 10.
时间: 2024-01-14 12:02:04 浏览: 84
AIX -命令参考大全(A-C)
Here's one possible implementation of the `cancellable` function in JavaScript:
```
function cancellable(fn, args, t) {
let timerId;
const promise = new Promise((resolve, reject) => {
timerId = setTimeout(() => {
resolve(fn(...args));
}, t);
});
const cancelFn = () => {
clearTimeout(timerId);
promise.then(() => {
console.log("Function call cancelled");
});
};
return cancelFn;
}
```
The `cancellable` function takes three arguments: `fn`, the function to be called after a delay; `args`, an array of arguments to pass to `fn`; and `t`, the delay time in milliseconds.
The function returns a cancel function `cancelFn`, which can be called to cancel the delayed function call. If `cancelFn` is called before the delay time is up, `fn` will never be called and the promise returned from `cancellable` will be rejected.
In the example given, you would call `cancellable` like this:
```
const cancel = cancellable((x) => x * 5, [2], 20);
```
This sets up a delayed call to `fn`, which multiplies its argument by 5. The argument is 2, so the expected result is 10. The delay time is 20ms, and the cancel time is 50ms.
To cancel the delayed call, you would call `cancel()`:
```
setTimeout(cancel, 50);
```
This cancels the delayed call at the specified cancel time. Since the cancel time is after the delay time, `fn` will be called at t=20ms and will return the value 10.
阅读全文