Skip to content

Instantly share code, notes, and snippets.

@xgqfrms
Created May 14, 2024 17:15
Show Gist options
  • Save xgqfrms/4d093b669bbbc0b09f7165bdbab1f617 to your computer and use it in GitHub Desktop.
Save xgqfrms/4d093b669bbbc0b09f7165bdbab1f617 to your computer and use it in GitHub Desktop.
LeetCode & Promise & cancelable

https://leetcode.com/problems/timeout-cancellation/?envType=study-plan-v2&envId=30-days-of-javascript

type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Fn = (...args: JSONValue[]) => void

function cancellable(fn: Fn, args: JSONValue[], t: number): Function {
  let id = setTimeout(() => fn(...args), t);
  // cancel delay
  return () => clearTimeout(id);
};

https://leetcode.com/problems/interval-cancellation/description/?envType=study-plan-v2&envId=30-days-of-javascript

type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Fn = (...args: JSONValue[]) => void

function cancellable(fn: Fn, args: JSONValue[], t: number): Function {
  // immediately called / setInterval 第一次立即执行
  fn(...args);
  // 💩 first call
  let id = setInterval(() => fn(...args), t);
  return () => clearInterval(id);
};

refs

https://www.cnblogs.com/xgqfrms/p/17687323.html

@xgqfrms
Copy link
Author

xgqfrms commented May 14, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment