Given a function fn, an array of arguments args, and an interval time t, return a cancel function cancelFn. The function fn should be called with args immediately and then called again every t millise
时间: 2024-03-20 16:44:33 浏览: 55
Sure, I can help you with that! Here's an example implementation in JavaScript:
```
function repeat(fn, args, t) {
const intervalId = setInterval(() => {
fn.apply(null, args);
}, t);
function cancelFn() {
clearInterval(intervalId);
}
fn.apply(null, args);
return cancelFn;
}
```
This function takes in three parameters: `fn` is the function to be called repeatedly, `args` is an array of arguments to be passed to `fn`, and `t` is the time interval in milliseconds.
The function sets up an interval using `setInterval` to repeatedly call `fn` with `args` every `t` milliseconds. It also immediately calls `fn` with `args` once before starting the interval.
The function returns a `cancelFn` function that can be used to cancel the interval and stop further calls to `fn`.
You can use this function like this:
```
const cancel = repeat(console.log, ['Hello!'], 1000);
// This will log 'Hello!' every second
// To cancel the interval, call the cancel function
cancel();
```
阅读全文