返回介绍

solution / 2800-2899 / 2805.Custom Interval / README_EN

发布于 2024-06-17 01:02:59 字数 3577 浏览 0 评论 0 收藏 0

2805. Custom Interval

中文文档

Description

Function customInterval

Given a function fn, a number delay and a number period, return a number id. customInterval is a function that should execute the provided function fn at intervals based on a linear pattern defined by the formula delay + period * count. The count in the formula represents the number of times the interval has been executed starting from an initial value of 0.

Function customClearInterval 

Given the id. id is the returned value from the function customInterval. customClearInterval should stop executing provided function fn at intervals.

Note: The setTimeout and setInterval functions in Node.js return an object, not a number.

 

Example 1:

Input: delay = 50, period = 20, cancelTime = 225
Output: [50,120,210]
Explanation: 
const t = performance.now()  
const result = []
        
const fn = () => {
  result.push(Math.floor(performance.now() - t))
}
const id = customInterval(fn, delay, period)

setTimeout(() => {
  customClearInterval(id)
}, 225)

50 + 20 * 0 = 50 // 50ms - 1st function call
50 + 20 * 1 = 70 // 50ms + 70ms = 120ms - 2nd function call
50 + 20 * 2 = 90 // 50ms + 70ms + 90ms = 210ms - 3rd function call

Example 2:

Input: delay = 20, period = 20, cancelTime = 150
Output: [20,60,120]
Explanation: 
20 + 20 * 0 = 20 // 20ms - 1st function call
20 + 20 * 1 = 40 // 20ms + 40ms = 60ms - 2nd function call
20 + 20 * 2 = 60 // 20ms + 40ms + 60ms = 120ms - 3rd function call

Example 3:

Input: delay = 100, period = 200, cancelTime = 500
Output: [100,400]
Explanation: 
100 + 200 * 0 = 100 // 100ms - 1st function call
100 + 200 * 1 = 300 // 100ms + 300ms = 400ms - 2nd function call

 

Constraints:

  • 20 <= delay, period <= 250
  • 20 <= cancelTime <= 1000

Solutions

Solution 1

const intervalMap = new Map<number, NodeJS.Timeout>();

function customInterval(fn: Function, delay: number, period: number): number {
  let count = 0;
  function recursiveTimeout() {
    intervalMap.set(
      id,
      setTimeout(() => {
        fn();
        count++;
        recursiveTimeout();
      }, delay + period * count),
    );
  }

  const id = Date.now();
  recursiveTimeout();
  return id;
}

function customClearInterval(id: number) {
  if (intervalMap.has(id)) {
    clearTimeout(intervalMap.get(id)!);
    intervalMap.delete(id);
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文