티스토리 뷰
- setTimeout 함수 실행시 t라는 시간이 지난 후 fn 함수 실행되도록 스케줄링 한다. setTimeout이 리턴하는 timeoutId를 변수에 담고, timeout 취소하는 clearTimeout 함수를 리턴한다.
type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Fn = (...args: JSONValue[]) => void
function cancellable(fn: Fn, args: JSONValue[], t: number): Function {
const timeoutId = setTimeout(() => {
fn(...args)
}, t)
return () => { clearTimeout(timeoutId) }
};
/**
* const result = [];
*
* const fn = (x) => x * 5;
* const args = [2], t = 20, cancelTimeMs = 50;
*
* const start = performance.now();
*
* const log = (...argsArr) => {
* const diff = Math.floor(performance.now() - start);
* result.push({"time": diff, "returned": fn(...argsArr)});
* }
*
* const cancel = cancellable(log, args, t);
*
* const maxT = Math.max(t, cancelTimeMs);
*
* setTimeout(cancel, cancelTimeMs);
*
* setTimeout(() => {
* console.log(result); // [{"time":20,"returned":10}]
* }, maxT + 15)
*/
댓글
