Skip to content

第 1 题:写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,...,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterVal #7

@lgwebdream

Description

@lgwebdream
Owner

欢迎在下方发表您的优质见解

Activity

Genzhen

Genzhen commented on Jun 22, 2020

@Genzhen
Collaborator
function mySetInterVal(fn, a, b) {
    this.a = a;
    this.b = b;
    this.time = 0;
    this.handle = -1;
    this.start = () => {
        this.handle = setTimeout(() => {
            fn();
            this.time++;
            this.start();
            console.log( this.a + this.time * this.b);
        }, this.a + this.time * this.b);
    }

    this.stop = () => {
        clearTimeout(this.handle);
        this.time = 0;
    }
}

var a = new mySetInterVal(() => {console.log('123')},1000, 2000 );
a.start();
a.stop();
luobolin

luobolin commented on Jul 12, 2020

@luobolin
export interface MySetInterValReturn {
    id: NodeJS.Timeout
}

export const mySetInterVal = (fn: (...args: any[]) => void, a: number, b: number): MySetInterValReturn => {
    let timeObj: MySetInterValReturn = { id: null }

    const helper = (timeout: number): void => {
        timeObj.id = setTimeout(() => {
            fn()
            helper(timeout + b)
        }, timeout);
    }

    helper(a)

    return timeObj
}

export const myClear = (timeObj: NodeJS.Timeout): void => {
    clearTimeout(timeObj)
}


// 测试用例
const timeObj = mySetInterVal((): void => {
    console.log(`time: ${new Date().getSeconds()}`)
}, 1000, 1000)


setTimeout(() => myClear(timeObj.id), 5000);
zk2401

zk2401 commented on Jul 13, 2020

@zk2401
function mySetInterVal(fn,a,b) {
    let timer={};
    function setOneTimer(fn,a,b){
        timer.id=setTimeout(()=>{
            console.log(a);
            fn();
            setOneTimer(fn,a+b,b);
        },a)
    }
    setOneTimer(fn,a,b);
    return timer;
}
function myClear(timer){
    clearTimeout(timer.id);
}

//test
const timer=mySetInterVal(()=>{console.log('run')},100,200);
setTimeout(()=>myClear(timer),2000);
Freeruning

Freeruning commented on Jul 13, 2020

@Freeruning
function mySetInterVal(fn, a, b) {
  let timeCount = 0;
  let timer
  const loop = () => {
    timer = setTimeout(() => {
      fn()
      timeCount++
      loop()
    }, a + timeCount * b)
  }
  loop()
  return () => {
    clearTimeout(timer)
  }
}
//测试
const myClear =mySetInterVal(()=>{console.log('test')},1000,500);
// 清除定时器
myClear()
leewr

leewr commented on Jul 14, 2020

@leewr

function mySetInterVal(fun, a, b) {
!mySetInterVal.prototype.maxLimit && (mySetInterVal.prototype.maxLimit = a + 2 * b)
if (a > mySetInterVal.prototype.maxLimit) {
mySetInterVal.prototype.maxLimit = null
return
}
return setTimeout(() => {
mySetInterVal(fun, a + b, b)
fun()
}, a);
}

function myClear(timeId) {
clearTimeout(timeId)
mySetInterVal.prototype.maxLimit = null

}

let timeId = mySetInterVal(() => {
console.log('----', timeId)
}, 1000, 1000)

ppoollaarr

ppoollaarr commented on Jul 14, 2020

@ppoollaarr

class mySetInterVal {
a: number;
b: number;
fn: (...args: any[]) => void;
handle: number;
count: number;

constructor(fn: (...args: any[]) => void, a: number, b: number) {
    this.a = a;
    this.b = b;
    this.fn = fn;
    this.count = 0;
}

start() {
    this.handle = setTimeout(() => {
        this.fn();
        this.count++;
        this.start();
        console.log(this.a + this.count * this.b);
    }, this.a + this.count * this.b);
}

stop() {
    clearTimeout(this.handle);
    this.count = 0;
}

}

let timeObj = new mySetInterVal(
() => {
console.log(1);
},
1000,
1000
);
timeObj.start();

shenanheng

shenanheng commented on Jul 14, 2020

@shenanheng
function mySetInterVal(fn, a, b) {
  // 停止的标识
  let obj = {
    timer: null,
  };
  let queue = [a, a + b, a + 2 * b];
  return () => {
    function run(arr) {
      if (arr.length) {
        obj.timer = setTimeout(() => {
          fn();
          run(arr);
        }, arr.shift());
      }
    }
    run(queue);
    return obj;
  };
}
function myClear(obj) {
  clearTimeout(obj.timer);
}
let obj = mySetInterVal(
  () => {
    console.log("在哪里");
  },
  1000,
  2000
)();
setTimeout(() => {
  myClear(obj);
}, 3000);
EmotionBin

EmotionBin commented on Jul 15, 2020

@EmotionBin
function mySetInterVal(fn, a, b) {
  let currentTimeout = null;
  let counter = 0;
  const step = () => {
    currentTimeout = setTimeout(() => {
      fn();
      counter === 2 ? counter = 0 : counter ++;
      step();
    }, a + counter * b);
  }
  step();
  return () => {
    clearTimeout(currentTimeout);
  }
}
const myClear = mySetInterVal(() => console.log(11), 1000, 2000);
// 11秒后停止
const id = setTimeout(() => {
  myClear();
  clearTimeout(id);
}, 11000);
cm-space

cm-space commented on Jul 15, 2020

@cm-space

function mySetInterVal(fn, a, b) {
this.a = a
this.b = b
this.time = 0
this.fn = fn
this.suspends=true
this.timer = null
}

mySetInterVal.prototype.strap = function () {
this.timer = function () {
setTimeout(() => {
this.fn()
this.time++
console.log(this.a + this.time * this.b)
if(this.suspends){
this.timer()
}
}, this.a + this.time * this.b)
}
this.timer()
}

mySetInterVal.prototype.suspend=function(){
this.suspends=false
}

let maybeCleanUpFn = new mySetInterVal(() => {
console.log('执行回调')
}, 1000, 2000)

maybeCleanUpFn.strap()

setTimeout(function () {
maybeCleanUpFn.suspend()
},100000)

Bobyoung0719

Bobyoung0719 commented on Jul 16, 2020

@Bobyoung0719

let timer = null;

function mySetInterVal(t1, t2) {
  const T = t1 + t2;

  if(t1 > 6000) {
    return myClear();
  }

  timer = setTimeout(() => {
    t2 += t1;
    
    mySetInterVal(t1, t2);
  }, T);
}

function myClear() {
  clearTimeout(timer);
}

mySetInterVal(1000, 1000);
HuberTRoy

HuberTRoy commented on Jul 16, 2020

@HuberTRoy
function getCurrentTime(a, b) {
    let cache = -1

    return function () {
        cache += 1
        return !cache ? a : a + cache*b
    }
}

function mySetInter(fn, a, b) {
    const _getCurrentTime = getCurrentTime(a, b)

    let clear = {
        timer: null
    }
    
    function _setTimeout() {
        return setTimeout(() => {
            fn();
            clear.timer = _setTimeout()
        }, _getCurrentTime())
    }

    clear.timer = _setTimeout()

    return clear
}

function myClear(timer) {
    clearTimeout(timer.timer)
}

let p = mySetInter(() => {console.log('hello world') }, 1000, 1000)

74 remaining items

Rednaxela-2

Rednaxela-2 commented on Jan 20, 2022

@Rednaxela-2

//第 1 题:写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,...,a+nb 的时间,然后写一个 myClear,停止上面的mySetInterVal
//本鼠鼠自我感觉良好,有无大佬指教一下捏,lkd勿扰
function mySetInterVal(fn,a,b,stopMoment) {
let count = 0, timer = null;
(function wrapperFun(time) {
timer = setTimeout(()=>{
fn();
console.log(程序运行了${count+1}轮,距离上一轮${a+count*b}毫秒)
count++;
wrapperFun(a+countb)
},time)
})(a+count
b);

setTimeout(()=>{
myClear(timer)
},stopMoment)

}

function myClear(timer) {
clearTimeout(timer)
}

mySetInterVal(()=>{console.log("输出测试文字");},1000,500,5000);

kangyana

kangyana commented on Feb 15, 2022

@kangyana
window.stack = {}
function mySetInterVal(fn, a, b) {
    var count = 0;
    var key = new Date().getTime();
    function loop() {
        var timer = setTimeout(() => {
            fn();
            count++;
            loop();
        }, a + count * b);
        window.stack[key] = timer;
    }
    loop();
    return key;
}
function myClear(key) {
    clearTimeout(window.stack[key]);
}

// 测试用例
const key = mySetInterVal(() => {
    console.log(123);
}, 1000, 1000)
setTimeout(() => {
    myClear(key);
}, 10000)
chihaoduodongxi

chihaoduodongxi commented on Feb 18, 2022

@chihaoduodongxi

function mySetInterVal(fn,a,b){
this.handle=0
this.timer=-1;
this.start=()=>{
this.timer=setTimeout(()=>{fn();this.handle++;this.start()},a+this.handle*b);
}
this.stop=()=>{clearTimeout(this.timer);}
}
let a=new mySetInterVal(()=>{console.log('123')},1000,1000);
a.start();
a.stop();

avenir-zhang

avenir-zhang commented on Feb 21, 2022

@avenir-zhang
function mySetInterVal(fn, a, b) {
  var timer = null, count = 0, isClear = false
  function createTimer () {
    if (isClear) return
    timer = setTimeout(() => {
      fn()
      clearTimeout(timer)
      createTimer()
    }, a + b * count)
  }
  createTimer()
  return function () {
    timer && (isClear = true, clearTimeout(timer))
  }
}
wmlgl

wmlgl commented on Mar 7, 2022

@wmlgl
    function mySetInterVal(fn, a, b) {
        var count = 0;
        var delay = a;
        var holder = {
            timer: null,
            stop: false
        };
        holder.timer = setTimeout(function () {
            if (holder.stop) {
                return;
            }
            try {
                fn();
            } catch (error) {
                console.error("mySetInterVal error: ", error);
            }
            count++;
            delay = a + count * b;
            console.log("mySetInterVal delay: " + delay);
            holder.timer = setTimeout(arguments.callee, delay);
        }, delay);

        return holder;
    };
    function myClear(interValHolder) {
        interValHolder.stop = true;
        clearTimeout(interValHolder.timer);
    }

    // test 
    console.log("start timer...");
    var timer = mySetInterVal(() => {
        console.log("onTimer...");
    }, 100, 200);

    setTimeout(() => {
        console.log("stop timer.")
        myClear(timer);
    }, 3000);
lang711

lang711 commented on Aug 25, 2022

@lang711
    function mySetInterval(fn, a = 1000, b = 1000) {
      let count = 0
      setTimeout(interval, a)
      function interval() {
        fn(setTimeout(interval, a + b * ++count))
      }
    }
    function myClear(id) {
      clearTimeout(id)
    }
    // 测试
    let count = 0
    mySetInterval((timer) => {
      console.log('test');
      count++
      if (count >= 5) {
        myClear(timer)
      }
    }, 1000, 1000)
huanmiezhicheng

huanmiezhicheng commented on Oct 25, 2022

@huanmiezhicheng

class MySetInterval {
constructor(fn, a, b) {
this.fn = fn
this.a = a
this.b = b
this.time = 0
this.handle = null
}
start() {
this.handle = setTimeout(() => {
this.fn()
this.time++
this.start()
}, this.a + this.time * this.b)
}
stop() {
clearTimeout(this.handle)
this.time = 0
}
}

let test = new MySetInterval(
() => {
console.log(111111)
},
1000,
2000
)
test.start()

captain-kuan

captain-kuan commented on Dec 14, 2022

@captain-kuan
const cache: number[] = []
let uid = 0
function mySetInterVal(fn: Function, a: number, b: number) {
    const _id = uid++
    function refresh() {
        cache[_id] = setTimeout(() => {
            fn(), refresh()
        }, b)
    }
    cache[_id] = setTimeout(() => {
        fn()
        refresh()
    }, a)
    return _id
}
function myClear(id: number) {
    clearTimeout(cache[id])
}
let id = mySetInterVal(() => {
    console.log(1);
}, 3000, 50)
let id2 = mySetInterVal(() => {
    console.log(2);
}, 50, 1000)
setTimeout(() => { myClear(id) }, 5000)
setTimeout(() => { myClear(id2) }, 15000)
Charles-ShiZ

Charles-ShiZ commented on Feb 22, 2023

@Charles-ShiZ
function mySetInterVal(fn:()=>void, a:number, b:number){
    let n = 0
    let delay = (n: number)=>{
        return a + n*b
    }
    function createTimeout (fn:()=>void) {
        const timeoutId = setTimeout(()=>{
            ++n
            fn()
            
            clearTimeout(timeoutId)
            createTimeout(fn)
        }, delay(n))
        return timeoutId
    }
    return createTimeout(fn)
}

function clearMySetInterVal(id: number){
    clearTimeout(id)
}

let last:number = 0
mySetInterVal(()=>{
    let seconds = new Date().getSeconds() || 60
    if(seconds < last ){
        seconds+=60
    }
    console.log(last ? seconds-last:1)
    last = seconds
}, 1000, 1000)
ResidualStar

ResidualStar commented on May 24, 2023

@ResidualStar

image

drlsxs

drlsxs commented on Jun 20, 2023

@drlsxs
function mySetInterVal(fn, a, b) {
    let timer = null;
    let count = 0;
    let step = (a) => {
        if (!timer && count) return;
        timer = setTimeout(() => {
            fn(count);
            count++;
            step(a + b);
        }, a);
    };
    step(a);

    let myClear = () => {
        timer = null;
        clearTimeout(timer);
        console.log(`执行结束,一共执行${count + 1}次`);
    };

    let counts = () => {
        return count;
    };

    return {
        myClear,
        counts,
    }
}


let fun  = mySetInterVal((n) => {
    console.log(`执行了${n + 1}次,时间为${1000+n*1000}`);
}, 1000, 1000);


setTimeout(() => {
    fun.myClear();
}, 10000);
Kisthanny

Kisthanny commented on Mar 20, 2024

@Kisthanny
let timerId; // 放在外部记录正在运行的计时器
function mySetInterVal(fn, a, b) {
  timerId = setTimeout(() => {
    fn();
    mySetInterVal(fn, a + b, b);
  }, a);
}
function myClear() {
  clearTimeout(timerId);
}

// 以下是测试用例

class Test {
  constructor() {
    this.startTime = 0;
    this.current = 0;
  }
  mySetInterVal() {
    this.startTime = Date.now();
    mySetInterVal(
      () => {
        this.current = Date.now();
        console.log(this.current - this.startTime);
        this.startTime = this.current;
      },
      100,
      50
    );
  }
}

const test = new Test();
test.mySetInterVal();

setTimeout(() => {
  console.log("stop");
  myClear();
}, 20000);
HenuAJY

HenuAJY commented on Apr 10, 2024

@HenuAJY
const runningSeed = new Set();
function mySetInterval(callback, a, b) {
  const seed = Symbol();
  runningSeed.add(seed);
  const run = (n) => {
    setTimeout(() => {
      if (!runningSeed.has(seed)) {
        return;
      }
      callback();
      run(n + 1);
    }, a + n * b);
  }
  run(0);
  return seed;
}
function myClearInterval(seed) {
  runningSeed.delete(seed);
}

// TEST
const start = Date.now();
const id = mySetInterval(() => {
  console.log(new Date());
	
  //10s 后停止
  if (Date.now() - start > 10000) {
    myClearInterval(id);
  }
}, 100, 100);
Amorcy

Amorcy commented on Sep 6, 2024

@Amorcy
function mySetInterVal (fn, a, b) {
  let delay = 0
  let shouldStop = false
  function start () {
    if (shouldStop) return
    const time = a + (delay++ * b)
    setTimeout(() => {
      fn()
      start()
    }, time)
  }
  start()
  function stop () {
    shouldStop = true
  }
  return stop
}

function myClear (cb) {
  cb()
}

// 用例
let count = 0
function fn () {
  console.log(++count)
}
const timer = mySetInterVal(fn, 1000, 500)

setTimeout(() => {
  myClear(timer)
}, 10000)
captain-kuan

captain-kuan commented on Sep 6, 2024

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @tinyfive@brianzhang@ruandao@roy2an@markduan

        Issue actions

          第 1 题:写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,...,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterVal · Issue #7 · lgwebdream/FE-Interview