EASY
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 milliseconds until cancelFn is called at cancelT ms.
給定一個函數fn
、一個參數陣列args
和一個間隔時間t
作為參數,並回傳一個取消函數cancelFn
。
應立即使用args
作為參數呼叫函數fn
,然後間隔t
毫秒再次呼叫,直到在cancelT
毫秒呼叫cancelFn
。
let result=[];
var cancellable = function (fn, args, t) {
let startTime = Date.now();
//宣告`callFn`-被調用時會呼叫`fn(...args)`並打印紀錄
let callFn =(...args) => {
let returnedVal = fn(...args);
const currentTime = Date.now();
const elapsedTime = currentTime - startTime;
console.log(`times:${elapsedTime},returned:${returnedVal}`);
result.push( {
'time':elapsedTime,
'returned':returnedVal,
});
}
callFn(...args); //第一次調用函數`callFn`
startTime = Date.now();
// 設定間隔幾秒調用一次`callFn`
let intervalID = setInterval(() => {
callFn(...args);
}, t);
//宣告`cancelFn`-被調用時會啟動倒計時以`取消間隔調用`
let cancelFn = () => {
clearInterval(intervalID);
};
return cancelFn;
};
let fn = (x) => x * 2;
let args = [4];
let t = 35; // t 单位是毫秒 0 35 70 105 140 175
const cancel = cancellable(fn, args, t);
let cancelT = 190; // cancelT 单位是毫秒
setTimeout(() => {
cancel();
console.log(result);
}, cancelT);
// output
// (6) [{…}, {…}, {…}, {…}, {…}, {…}]
// 0: {time: 0, returned: 8}
// 1: {time: 47, returned: 8}
// 2: {time: 78, returned: 8}
// 3: {time: 109, returned: 8}
// 4: {time: 156, returned: 8}
// 5: {time: 187, returned: 8}
let fn = (x1, x2) => (x1 * x2);
let args = [2, 5];
let t = 30; // t 单位是毫秒 0 35 60 90 120 150
const cancel = cancellable(fn, args, t);
let cancelT = 165; // cancelT 单位是毫秒
setTimeout(() => {
cancel();
console.log(result);
}, cancelT);
// output
// (6) [{…}, {…}, {…}, {…}, {…}, {…}]
// 0: {time: 0, returned: 10}
// 1: {time: 31, returned: 10}
// 2: {time: 61, returned: 10}
// 3: {time: 90, returned: 10}
// 4: {time: 120, returned: 10}
// 5: {time: 151, returned: 10}
let fn = (x1, x2, x3) => (x1 + x2 + x3);
let args = [5, 1, 3];
let t = 50; // t 单位是毫秒 0 50 100 150
const cancel = cancellable(fn, args, t);
let cancelT = 180; // cancelT 单位是毫秒
setTimeout(() => {
cancel();
console.log(result);
}, cancelT);
//output
// (4) [{…}, {…}, {…}, {…}]
// 0: {time: 0, returned: 9}
// 1: {time: 64, returned: 9}
// 2: {time: 110, returned: 9}
// 3: {time: 156, returned: 9}