GithubHelp home page GithubHelp logo

第 1 题:写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,...,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterVal about fe-interview HOT 92 OPEN

lgwebdream avatar lgwebdream commented on May 1, 2024
第 1 题:写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,...,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterVal

from fe-interview.

Comments (92)

Genzhen avatar Genzhen commented on May 1, 2024 234
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();

from fe-interview.

Freeruning avatar Freeruning commented on May 1, 2024 88
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()

from fe-interview.

luobolin avatar luobolin commented on May 1, 2024 21
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);

from fe-interview.

zk2401 avatar zk2401 commented on May 1, 2024 19
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);

from fe-interview.

Z6T avatar Z6T commented on May 1, 2024 17
// 没有人比我的代码更短!
function mySetInterVal(fn, a, b) {
  let timer= setTimeout(() => {
      fn()
      mySetInterVal(fn,a+b,b)
    }, a)
  return () => {
    clearTimeout(timer)
  }
}
const myClear =mySetInterVal(()=>{console.log('abc')},1000,500);
// 清除定时器
myClear()

from fe-interview.

Rednaxela-2 avatar Rednaxela-2 commented on May 1, 2024 11

//第 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);

from fe-interview.

18602435705 avatar 18602435705 commented on May 1, 2024 5
function interVal(cb, a, b) {
  let timer = null;
  const recursion = (delay) => {
    timer = setTimeout(() => {
      cb();
      recursion(delay + b);
    }, delay);
  };
  recursion(a);
  return () => clearInterval(timer);
}

// 测试
const clear = interVal(() => console.log("haha"), 1000, 500);
// 清除定时器
setTimeout(clear, 5000);

// 递归自带累加功能,不需要额外的计数器

from fe-interview.

jesse-li avatar jesse-li commented on May 1, 2024 4
// 没有人比我的代码更短!
function mySetInterVal(fn, a, b) {
  let timer= setTimeout(() => {
      fn()
      mySetInterVal(fn,a+b,b)
    }, a)
  return () => {
    clearTimeout(timer)
  }
}
const myClear =mySetInterVal(()=>{console.log('abc')},1000,500);
// 清除定时器
myClear()

有问题 return 的timer是第一次的timer,改一下

function mySetInterVal(fn, a, b) {
   let timer = null;
    (function test(fn,a,b){
    timer = setTimeout(() => {
          fn()
          test(fn,a+b,b)
        }, a);
})(...arguments)
  return () => {
    clearTimeout(timer)
  }
}
var myClear =mySetInterVal(()=>{console.log('abc')},1000,500);

from fe-interview.

Bobyoung0719 avatar Bobyoung0719 commented on May 1, 2024 3

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);

from fe-interview.

xiaoxiaocoder avatar xiaoxiaocoder commented on May 1, 2024 3
 function mySetInterVal(fn, a, b) {
   // 执行次数
  let times = 0;
  // 计时器
  let timerId
  function _interval()  {
      let duration = a + times * b;
      // 清除前一次的timeout
      timerId && clearTimeout(timerId)
      timerId = setTimeout(function() {
        fn.call(null)
        times++;
        _interval()
    }, duration)
  }
  _interval();
  return function clear(){
    timerId && clearTimeout(timerId)
  }
 }

const myClear = mySetInterVal(() => console.log('hello world'), 100, 200)

setTimeout(myClear, 2000)

from fe-interview.

leewr avatar leewr commented on May 1, 2024 1

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)

from fe-interview.

EmotionBin avatar EmotionBin commented on May 1, 2024 1
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);

from fe-interview.

cm-space avatar cm-space commented on May 1, 2024 1

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)

from fe-interview.

WebTzx avatar WebTzx commented on May 1, 2024 1
function mySetInterval (fn, a, b) {
    let _interval = [];
    let clear;
    const timeout = () => {
        clear = setTimeout( () => {
            fn();
            if (_interval.length) timeout();
        }, _interval.shift() )
    };

    this.myClear = () => clearTimeout( clear );
    this.start = () => {
        _interval = [ a, a + b, a + (2 * b) ];
        timeout();
    }
};

const runInterval = new mySetInterval( () => console.log('run'),  1000, 2000 )

from fe-interview.

GolderBrother avatar GolderBrother commented on May 1, 2024 1
// 第 1 题:写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b 的时间,然后写一个 myClear,停止上面的 mySetInterVal
// export {};
class MySetInterval {
  constructor(fn, a, b) {
    this.a = a;
    this.b = b;
    this.fn = fn;
    this.timer = null;
    this.times = 0;
  }

  start() {
    this.timer = setTimeout(() => {
      typeof this.fn === "function" && this.fn();
      this.times++;
      this.start();
      console.log(`this.a + this.times * this.b`, this.a + this.times * this.b);
    }, this.a + this.times * this.b);
  }

  stop() {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    this.times = 0;
  }
}

const mySetInterval = new MySetInterval(
  () => {
    console.log("123");
  },
  1000,
  2000
);
mySetInterval.start();
mySetInterval.stop();

from fe-interview.

m7yue avatar m7yue commented on May 1, 2024 1
class Interval {
  timer = null;
  count = 0;

  constructor(fn, a, b) {
    this.a = a;
    this.b = b;
    this.fn = fn;
  }

  mySetInterVal(){
    this.timer = setTimeout(() => {
      this.fn();
      this.count++;
      this.mySetInterVal();
    }, this.a+this.count*this.b)
  }

  myClear() {
    clearTimeout(this.timer);
  }
}

export default interval;

const interval = new Interval(() => console.log(777), 1000, 1000);
interval.mySetInterVal()

setTimeout(() => interval.myClear(), 5000)

from fe-interview.

zengxiaoluan avatar zengxiaoluan commented on May 1, 2024 1
function mySetInterval(fn, a, b) {
    let index = 0
    let timeId

    inner()
    return function myClearInterval() {
        clearTimeout(timeId)
    }
    function inner() {
        timeId = setTimeout(() => {
            fn()
            inner() // 调用自身
        }, a + index * b)
        index++
    }
}

// 下面是测试的例子
let last = Date.now()
var myClearInterval = mySetInterval(() => {
    let now = Date.now()
    console.log(Math.round((now - last) / 1000))
    last = now
}, 1000, 1000)

from fe-interview.

renwanjun avatar renwanjun commented on May 1, 2024 1
function mySetInterVal(fn, a, b) {
    let id = null
    function innerSetTimeout(init, interval) {
        // console.time('global')
        return setTimeout(() => {
            fn()
            // console.timeEnd('global')
            id = innerSetTimeout(init + interval, interval)
        }, init)
    }
    id = innerSetTimeout(a, b)
    return () => {
        clearTimeout(id)
    }
}
const myClear = mySetInterVal(() => { console.log('hhh') }, 100, 0)
setTimeout(myClear, 8000)

from fe-interview.

0xe69e97 avatar 0xe69e97 commented on May 1, 2024 1
let timer = null
function mySetInterVal(fn, a, b) {
    let count = 0

    execute = (fn, time = a) => {
        timer = setTimeout(() => {
            if (timer !== null) {
                execute(fn, a + b * count)
            }
            console.log(a + b * count + 'ms')
            fn()
            count++
        }, time)
    }

    execute(fn)
}

function myClear() {
    clearTimeout(timer)
    timer = null
    console.log('Stop!')
}

let sum = 0

mySetInterVal(() => console.log(`第 ${++sum} 次调用`), 1000, 2000)


const stopTime = 5000 // 5 秒后停止

setTimeout(() => {
    myClear()
}, 5000);

from fe-interview.

Mis-tian avatar Mis-tian commented on May 1, 2024 1
    const Step = new Proxy({
        id: 0,
        n: 0,
        timeout: 0,
        a: 0,
        b: 0,
        fn: null,
        mySetInterVal(fn, a, b){
            this.fn = fn;
            this.a = a;
            this.b = b;
            this.myStart()
        },
        myStart() {
            this.id = setTimeout(()=>{
                this.fn && this.fn(this)
                this.n ++ 
                this.myStart()
            }, this.timeout)
        },
        myClear() {
            clearTimeout(this.id)
        }
    }, 
    {
        set: function(obj, prop, value) {
            if ( prop === 'n') {
                obj.timeout = obj.a + (value * obj.b);
            }
            obj[prop] = value;
            return obj;
        },
        get: function(obj, prop) {
            if (prop === 'timeout') {
                return obj.a + (obj.n * obj.b)
            }
            return obj[prop];
        },
    });
    Step.mySetInterVal((v)=>{
        console.log('run', v)
    }, 1000, 1000);
    // Step.myClear()

from fe-interview.

yeyeyehui avatar yeyeyehui commented on May 1, 2024 1

// 试一试写一个自定义hooks实现

import React, {useRef} from 'react'

const useMySetInterVal = (fn, a, b) => {
    const optionData = useRef({
      fn,
      a,
      b,
      time: 0,
      handel: null
    }).current

  const mySetInterVal = () => {
    const {fn, a, b, time} = optionData
    optionData.handel = setTimeout(() => {
      fn()
      optionData.time = time + 1
      mySetInterVal()
    }, a + b * time)
  }

  const myClear = () => {
    clearTimeout(optionData.handel)
    optionData.handel = null
    optionData.time = 0
  }

  return {mySetInterVal, myClear}
}

function App() {
  const {mySetInterVal, myClear} = useMySetInterVal(() => {console.log('ss')}, 1000, 1000)

  return (
    <div className="App">
      <p onClick={mySetInterVal}>123</p>
      <p onClick={myClear}>456</p>
    </div>
  );
}

from fe-interview.

kangyana avatar kangyana commented on May 1, 2024 1
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)

from fe-interview.

ppoollaarr avatar ppoollaarr commented on May 1, 2024

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();

from fe-interview.

shenanheng avatar shenanheng commented on May 1, 2024
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);

from fe-interview.

HuberTRoy avatar HuberTRoy commented on May 1, 2024
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)

from fe-interview.

Marckon avatar Marckon commented on May 1, 2024

题目不太清晰啊,是每次间隔以此类推吧

from fe-interview.

Genzhen avatar Genzhen commented on May 1, 2024

题目不太清晰啊,是每次间隔以此类推吧

@Marckon
是有点,改了,感谢提出问题

from fe-interview.

Funwentao avatar Funwentao commented on May 1, 2024
function mySetInterVal(fn, a, b) {
    let timeOut = {
        timeOutId: 0,
        intervalId: 0
    }
    timeOut.timeOutId = setTimeout(() => {
        fn()
        timeOut.intervalId = setInterval(fn, b)
    }, a)
    return timeOut
}
function myClear(timeOut){
    clearTimeout(timeOut.timeOutId)
    clearInterval(timeOut.intervalId)
}

from fe-interview.

xyydd avatar xyydd commented on May 1, 2024

讲真,我觉得我这个有点东西

function mySetInterVal (fn, a, b) {
    let handle = {
        i: 0,
        stop: false
    }
    let realIntFn = function () {
        let set
        if (!handle.stop) {
            set = setTimeout(() => {
                console.log(`a + ${handle.i}b`, a + b * handle.i)
                fn()
                handle.i++
                realIntFn()
            }, a + b * handle.i)
        } else {
            clearTimeout(set)
        }
    }
    realIntFn()
    return {
        stop: function () {
            handle.stop = true
        }
    }
}

function myClear (intVal) {
  intVal.stop()
}

 module.exports = {
    mySetInterVal,
    myClear
 }
// 测试 test.js
const { mySetInterVal, myClear } = require('./mySetIntVal.js')

const s = mySetInterVal(() => {
  console.log(s)
}, 1000, 1000)

setTimeout(() => {
  myClear(s)
}, 6000)

from fe-interview.

brianzhang avatar brianzhang commented on May 1, 2024
// code by brian.netmad@gmail.com
function mySetInterVal(fn, a, b) {
  this.a = a;
  this.b = b;
  this.time = 0;
  this.handle = null;
  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.start()
  this.stop = () => {
    clearTimeout(this.handle)
    this.time = 0;
    console.log('执行已被清理,结束执行')
  }
  return this.stop
}
let myClear = mySetInterVal(function() {console.log('间隔执行了')}, 1000, 1000);

setTimeout(myClear, 10000)

from fe-interview.

z253573760 avatar z253573760 commented on May 1, 2024

function mySetInterVal(fn, a, b) {
  let step = 0
  let timer = null
  const create = (timeout) => {
    timer = setTimeout(() => {
      fn(a + step * b)
      step += 1
      create(a + step * b)
    }, timeout);
  }
  create(a + step * b)
  return {
    myClear() {
      console.log("结束了")
      clearTimeout(timer)
    }
  }
}
const {
  myClear
} = mySetInterVal((val) => console.log(val), 1000, 1000)

setTimeout(() => {
  myClear()
}, 10000)

from fe-interview.

shihongchun avatar shihongchun commented on May 1, 2024
let i = 0;
function log() {
    console.log(i++);
}
function wait(time = 300) {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, time);
    });
}
function mySetInterVal(fn, a, b) {
    this.switchBol = true;
    this.limitTime = a;
    const vm = this;
    (async () => {
        while(vm.switchBol) {
            await wait(vm.limitTime);
            fn();
            vm.limitTime += b;
        }
    })();
    return vm;
}
function myClear(timer) {
    timer.switchBol = false;
}

const timer = mySetInterVal(log, 1000, 1000);
// 测试
setTimeout(() => {
    myClear(timer);
}, 5000);

from fe-interview.

huzedong2015 avatar huzedong2015 commented on May 1, 2024
function mySetInterVal(fn, a, b) {
    const maxLen = 3;
    let index = 0;

    function callback() {
        if (index >= 0) {
            return;
        }

        const current = a + b * (index % maxLen);

        setTimeout(() => {
            index++;

            if (index >= 0) {
                fn(current);
                callback();
            }
        }, current);
    }

    callback();

    return function() {
        index = -2;
    };
    
};

const setInterValStop = mySetInterVal((time) => {
    console.log(time);
}, 1000, 2000);

function myClear() {
    setInterValStop();
}

from fe-interview.

chaos1ee avatar chaos1ee commented on May 1, 2024

借鉴前面的思路,通过对象传递的是引用的特性,获取timeout id

function mySetInterVal(fn, a, b) {
  const timer = {};

  function circle(duration) {
    myClear(timer);

    timer.id = setTimeout(() => {
      fn();

      circle(duration + b);
    }, duration);

    return timer;
  }

  return circle(a);
}

function myClear(timer) {
  if (timer.id) {
    clearTimeout(timer.id);
  }
}

const foo = () => {
  console.log("a");
};

const timer = mySetInterVal(foo, 1000, 1000);

setTimeout(() => {
  myClear(timer);
}, 5000);

from fe-interview.

colincxz avatar colincxz commented on May 1, 2024

function mySetInterVal(fn, a, b) {
  let timer;
  function timeout(fn, i) {
    timer = setTimeout(() => {
      fn();
      timeout(fn, i + 1);
    }, a + i * b);
  }
  timeout(fn, 0);

  function getTimer() {
    return timer;
  }

  return getTimer;
}

let getTimer = mySetInterVal(() => {
  console.log(Math.ceil(Date.now() / 1000));
}, 1000, 1000);


function myCelar(timer) {
  clearTimeout(timer);
}

setTimeout(() => {
  myCelar(getTimer())
}, 10000);

from fe-interview.

 avatar commented on May 1, 2024

function mySetInterval(fn, a, b) {
let timeId = {};
(function timeCircle(timeId, fn, a, b) {
timeId.id = setTimeout(() => {
fn();
timeCircle(timeId, fn, a+b, b);
}, a);
})(timeId, fn, a, b);
return timeId
}

function myClear(timeId){
clearTimeout(timeId);
}

//test
let timeId = mySetInterval(function(){
console.log(Date.now());
}, 1000, 1000);
setTimeout(() => {
myClear(timeId.id);
}, 10000);

from fe-interview.

carbrokers avatar carbrokers commented on May 1, 2024
function mySetInterVal(fn, a, b) {
  let interval = null
  let count = 0;

  function delayFn() {
    interval = setTimeout(function() {
      fn();
      count++;
      delayFn();
    }, a + count * b);
  }

  delayFn()
  return function() {
    clearInterval(interval);
  };
}

from fe-interview.

467057463 avatar 467057463 commented on May 1, 2024
function mySetInterVal(fn, a, b){
  let count = 0;
  let timer;

  (function loop(){
    timer = setTimeout(()=> {
      fn()
      count ++;
      loop()
    }, a + b * count)
  })()  

  return function(){
    clearTimeout(timer)
  }
}

let myClear = mySetInterVal(() => console.log('hello'), 1000, 1000)

from fe-interview.

Coiven avatar Coiven commented on May 1, 2024
var mySetInterval = (fn, a, b) => {
  let i = 0;
  let obj = {
    timer: -1,
  };

  const clear = () => {
    clearTimeout(obj.timer);
  };

  const start = () => {
    obj.timer = setTimeout(() => {
      fn();
      clear();
      start();
    }, a + i++ * b);
  };

  return {
    start,
    clear,
  };
};

// test
const { start, clear } = mySetInterval(() => console.log("test"), 2e3, 2e3);
start();
clear();

from fe-interview.

miyizs avatar miyizs commented on May 1, 2024
let timer;
let count = -1;
function mySetInterval(a, b, fn) {
    count++;
    timer = setTimeout(() => {
        fn();
        console.log(count);
        console.log(a + count * b);
        mySetInterval(a, b, fn)
    }, a + count * b)
}

mySetInterval(1000, 2000, () => { console.log('111') });
clearTimeout(timer);

from fe-interview.

noney avatar noney commented on May 1, 2024
/**
 * [mySetInterVal description]
 * @param  {Function} fn [函数]
 * @param  {[type]}   a  [开始时间]
 * @param  {[type]}   b  [累加时间]
 * @return {[type]}      [description]
 */
function mySetInterVal(fn, a, b) {
  let count = 0;
  let myClear = () => {
    timer && clearTimeout(timer);
    count = 0;
  }
  let timer = setTimeout(function f() {
    if (count > 10) {
      myClear();
      count = 0;
      return;
    }
    fn(a, count, b);
    count++;
    timer = setTimeout(f, a + count * b);
  }, a)
}

mySetInterVal((a, count, b) => console.log(`a: ${a} count: ${count} b: ${b} ${a}+${count}*${b}: ${a + count * b}`), 1000, 2000);

from fe-interview.

ruandao avatar ruandao commented on May 1, 2024
const mySetInterval = (fn, a, b) => {
    let timer
    const start = (fn, a, b) => {
        timer = setTimeout(() => {
            fn();
            timer = start(fn, a+b, b);
        }, a, b);
    }
    start(fn, a, b)

    return () => {
        clearTimeout(timer)
    }
}

from fe-interview.

chengazhen avatar chengazhen commented on May 1, 2024
 class MysetInterVal {
      constructor() {
        this.index = 0
      }
      start(a, b, func) {
        let times = a + this.index * b;
        this.timer = setTimeout(() => {
          func()
          this.index++;
          this.start(a, b,func)
        }, times)
      }
      stop(time) {
        clearTimeout(this.timer)
        this.index = 0
      }
    }
    const mysetInterVal = new MysetInterVal();
    mysetInterVal.start(500, 500, () => { console.log(new Date()) })

from fe-interview.

markduan avatar markduan commented on May 1, 2024
function mySetInterVal(fn, a, b) {
  let timeoutID;
  let count = 0;

  function scheduleExecution(func, delay) {
    timeoutID = setTimeout(() => {
      func();

      count = count + 1;
      scheduleNextExecution(func, count)
    }, delay);
  }

  function scheduleNextExecution(func, executionCount) {
    console.log('schedule next execution:', a + executionCount * b);
    scheduleExecution(func, a + executionCount * b)
  }

  scheduleNextExecution(fn, count);

  return () => clearTimeout(timeoutID);
}

const myFunc = () => {
  console.log(new Date());
};

const myClear = mySetInterVal(myFunc, 1000, 2000);

from fe-interview.

daiwa233 avatar daiwa233 commented on May 1, 2024
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();

startstop 函数在构造函数中初始化不太好,显得很臃肿,而且完全没有必要使用面向对象的方法解答

from fe-interview.

 avatar commented on May 1, 2024
mySetInterval = (fn,a,b) => {
    let running = true;
    let count = 0;

    function loop(){
        setTimeout(() => {
            if(running === true){
                fn();
                count++;
                loop();
            } 
        }, a + count*b)
    }
    loop();
    return () => {
        running = false
    };
}

myClearInterval = (shutdown) => {
    shutdown();
}

from fe-interview.

Evllis avatar Evllis commented on May 1, 2024

// 没有人比我的代码更短!

function mySetInterVal(fn, a, b) {

let timer= setTimeout(() => {

  fn()
  mySetInterVal(fn,a+b,b)
}, a)

return () => {

clearTimeout(timer)

}

}

const myClear =mySetInterVal(()=>{console.log('abc')},1000,500);

// 清除定时器

myClear()

有问题 return 的timer是第一次的timer,改一下

function mySetInterVal(fn, a, b) {

   let timer = null;

    (function test(fn,a,b){

    timer = setTimeout(() => {

          fn()

          test(fn,a+b,b)

        }, a);

})(...arguments)

  return () => {

    clearTimeout(timer)

  }

}

var myClear =mySetInterVal(()=>{console.log('abc')},1000,500);

和我的想法一样,哈哈。

from fe-interview.

tinyfive avatar tinyfive commented on May 1, 2024

为了保持和原生 setInterval 一致,mySetInterval 和 myClear 都是函数,调用方法都一样,并没有搞成类

function mySetInterval(fn, a, b) {
  let x = 0;
  let timer = { active: null };

  const nextTick = () => a + x * b;

  const recursiveFunc = () => {
    fn();
    x++;
    timer.active = setTimeout(recursiveFunc, nextTick());
  };

  timer.active = setTimeout(recursiveFunc, nextTick());

  return timer;
}

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

// Test

const a = 500;
const b = 1000;

const timer = mySetInterval(() => {
  const now = new Date();
  console.log(now.getTime());
  console.log(timer);
}, a, b);

setTimeout(() => {
  myClear(timer);
}, a + 20 * b);

from fe-interview.

systemctls avatar systemctls commented on May 1, 2024
function mySetInterVal(fn, a, b) {
      let timeCount = 0
      let timer
			const startLoop = () => {
        timer = setTimeout(()=>{
          fn()
          timeCount+=1
          startLoop()
        },a + timeCount * b)
      }
      const stopLoop = () => {
        clearTimeout(timer)
      }
      return {
        start: startLoop,
        stop:  stopLoop
      }
    }
   
 let loop = mySetInterVal(()=>{console.log('2-2-2-2')},1000,2000)
 loop.start();
loop.stop();

from fe-interview.

lion1ou avatar lion1ou commented on May 1, 2024
function mySetInterVal(fn, a, b) {
  let index = 0;
  let timer = null;
  let stopTimer = false;
  function mySetTimeout(fn, t) {
    if (!stopTimer) {
      timer = setTimeout(() => {
        fn();
        index++;
        mySetTimeout(fn, a + index * b);
      }, t);
    } else {
      clearTimeout(timer);
    }
  }
  mySetTimeout(fn, a);
  return {
    stop: () => {
      stopTimer = true;
    },
  };
}

function clearMyInterVal(timer) {
  timer.stop();
}

// 测试代码

let lastTime = new Date().getTime();
let time = 0;
let sI = mySetInterVal(
  () => {
    let now = new Date().getTime();
    console.log("间隔时间:", now - lastTime);
    lastTime = now;
    time++;
    if (time >= 3) {
      clearMyInterVal(sI);
    }
  },
  1000,
  200
);

from fe-interview.

liurongqing avatar liurongqing commented on May 1, 2024
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(testTimer),2000);

我感觉这个挺好的,比较容易理解

  1. timer 与 testTimer 统一一下名字
  2. 然后timer直接一个变量就行了吧,不用创建一个对象吧

from fe-interview.

JSerZANP avatar JSerZANP commented on May 1, 2024

https://bigfrontend.dev/problem/create-an-interval
https://bigfrontend.dev/problem/create-an-interval/discuss
这里也有一些答案

from fe-interview.

InterfaceBoy avatar InterfaceBoy commented on May 1, 2024

class Point {
constructor(data) {
const {a,b}=data;
this.a = a;
this.b = b;
this.time = 0;
}
compile(){
console.log("开始执行");
this.stop = setTimeout(() => {
this.time++;
this.compile();
console.log("执行中",this.a + this.time * this.b);
}, this.a + this.time * this.b);
}
compileStop(){
clearTimeout(this.stop);
console.log("停止执行");
}
}
const point = new Point({a:1000,b:1000});
point.compile();
point.compileStop();

from fe-interview.

BrucelLi avatar BrucelLi commented on May 1, 2024
 function mySetTimeout(fn, a, b) {
    this.a = a;
    this.b = b;
    this.times = 0;
    this.timer = null;
    this.start = () => {
      this.timer = setTimeout(() => {
        fn();
        console.log('mySetTimeout time:', this.times);
        console.log('mySetTimeout:', this.a + this.times * this.b);
        this.times++;
        this.start();
      }, a + this.times * this.b);
    }
    this.stop = () => {
      if (this.timer) {
        clearTimeout(this.timer);
        this.times = 0;
        console.log('mySetTimeout stop');
      }
    }
  }
  var timeObj = new mySetTimeout(() => {
    console.log('test');
  }, 100, 200);
  timeObj.start();

  var tTimer = setTimeout(() => {
    timeObj.stop();
    clearTimeout(tTimer);
  }, 1000);

from fe-interview.

MrLuo2020 avatar MrLuo2020 commented on May 1, 2024

function mySetInterVal(fn, a, b) {

   let count = -1
    let flg = null
    let f = () => {
    flg = setTimeout(() => {
        count++
        console.log(a + b * count)
        f()
        fn()
    }, a + b * count)
    }
    f()
   return function myClear(s) {
    setTimeout(() => {
        clearTimeout(flg)
    }, 1000*s);
    }
}
let myClear = mySetInterVal(
   () => {
    console.log('123')
    },
    3000,
    1000
)
myClear(20)// 3s+ 4s+ 5s+ 6s =18s 20s后会强制取消'`

from fe-interview.

frankd318 avatar frankd318 commented on May 1, 2024

setTimeout 递归

// CODE
const myInterval = (fn, a, b) => {
    let timer = -1
    let count = 0

    let createTimer = () => {
        timer = setTimeout(() => {
            createTimer()
            fn(count++)
        }, a + count * b)
    }

    createTimer()

    return () => {
        clearTimeout(timer)
        timer = -1
    }
}

// test
console.log('\nstart\n')

const myClear = myInterval(
    count => console.log(count, new Date()),
    50,
    100
)

setTimeout(myClear, 10000)

from fe-interview.

martianmartian avatar martianmartian commented on May 1, 2024
// 没有人比我的代码更短!
function mySetInterVal(fn, a, b) {
  let timer= setTimeout(() => {
      fn()
      mySetInterVal(fn,a+b,b)
    }, a)
  return () => {
    clearTimeout(timer)
  }
}
const myClear =mySetInterVal(()=>{console.log('abc')},1000,500);
// 清除定时器
myClear()

这个会有内存泄漏吗?let 每次都要保留一个{ }?

function fn(a,b){console.log('---lol---',a,b);}

var stopper=false;
function mySetInterVal(fn,a,b){
setTimeout(() => {
if(stopper){return}
fn(a,b);
mySetInterVal(fn,a+b,b);
}, a+b);
}
function myClear(){
stopper=true;
}

mySetInterVal(fn,500,500);

from fe-interview.

xiaomeng7586 avatar xiaomeng7586 commented on May 1, 2024

function mySetInterVal(fn, a, b){
let number = 0,timeObj = {0:a,1:b,2:a+b},timers={value:null};
function getTimer(){
return setTimeout(()=>{
fn();
number = number>=2?0:++number
timers.value = getTimer();
console.log(timeObj[number])
},timeObj[number])
}
timers.value = getTimer();
return timers
}
function myClear(timer){
clearTimeout(timer.value)
}
var timers = mySetInterVal(function(){
console.log(new Date().getSeconds())
},1000,2000)
myClear(timers)

from fe-interview.

qq820137708 avatar qq820137708 commented on May 1, 2024
function mySetInterVal(fn, a, b) {
    this.a = a;
    this.b = b;
    this.time = 0;
    this.handle = null;

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

    this.end = () => {
        clearTimeout(this.handle);
        this.time = 0;
    }
}
function test() {
    return console.log('调用时间:' + new Date().toTimeString().slice(0, 8))
}
const demo = new mySetInterVal(test, 1000, 2000 );
demo.start();
demo.end();

from fe-interview.

JosueZ avatar JosueZ commented on May 1, 2024

/**

  • 写一个 mySetInterVal(fn, a, b),
  • 每次间隔 a, a+b, a+2b, ..., a+nb 的时间
  • 然后写一个 myClear,停止上面的 mySetInterVal
    */
    class MySetInterVal {
    constructor (fn, a, b) {
    this.a = a
    this.b = b
    this.fn = fn
    this.times = 0 // 计数器
    this.timeout = null
    }
    // 开始
    start () {
    this.timeout = setTimeout(() => {
    this.fn()
    this.times++
    this.start()
    console.log('间隔了:', this.a + this.times * this.b)
    }, this.a + this.times * this.b)
    }
    // 清除
    myClear () {
    clearTimeout(this.timeout)
    this.times = 0
    }
    }

const mySetInterVal = new MySetInterVal(() => { console.log('123') }, 1000, 2000)
mySetInterVal.start()
// mySetInterVal.myClear()

from fe-interview.

geekftz avatar geekftz commented on May 1, 2024

function produce(fn, a, b) {
var mySetInterVal, myClear; // 函数
var num = 0; // 起始值
var timer;

mySetInterVal = () => {
timer = setTimeout(() => {
fn();
num++;
mySetInterVal();
}, a + num * b);
};

myClear = () => {
clearTimeout(timer);
num = 0;
};

return [mySetInterVal, myClear];
}

var loop = () => {
console.log('loop called');
};

var [mySetInterVal, myClear] = produce(loop, 1000, 2000);

from fe-interview.

Luoyuda avatar Luoyuda commented on May 1, 2024
    function mySetInterVal(fn, a, b){
        var timeId
        var i = 0
        var setInterval = () =>{
            timeId = setTimeout(() => {
                clearTimeout(timeId)
                fn()
                console.log(a, b, (a + i * b))
                i++
                setInterval()
            }, (a + i * b) * 1000)
        }
        setInterval()
        return function(){
            clearTimeout(timeId)
        }
    }
    
    var clear = mySetInterVal(function(){
        console.log('a')
    }, 1, 1)
    setTimeout(() => {
        clear()
    }, 5000)

from fe-interview.

SnailOwO avatar SnailOwO commented on May 1, 2024
// generator实现
function mySetInterVal(fn) {
        let cur = g.next()
        let timer = null
        if (!cur.done) {
            timer = setTimeout(() => {
                    fn.call(this)
                    mySetInterVal(fn)
                }, cur.value * 1000) // 1 3 5
        } else {
            myClear(timer)
        }
    }

    function myClear(id) {
        clearTimeout(id)
        console.log('cleared')
    }

    function* getTime(a, b) {
        yield a
        yield a + b
        yield a + 2 * b
    }

    const g = getTime(1, 2)
    mySetInterVal(() => {
            console.log('233')
        })

// 重新审题后
 let timer = null

    function mySetInterVal(fn, a, b) {
        timeFn(fn, a, b)
    }

    function timeFn(fn, a, b, i = 0) {
        let tag = a + i * b
        timer = setTimeout(() => {
            console.log(i, tag)
            fn.call(this)
            timeFn(fn, a, b, ++i)
                // myClear(timer)
        }, tag * 1000)
    }

    function myClear(timer) {
        console.log(`timer:${timer}`)
        clearTimeout(timer)
    }

    mySetInterVal(() => {
            console.log(233)
        }, 1, 2)
`

from fe-interview.

xcp0326 avatar xcp0326 commented on May 1, 2024
const mySetInterVal = (fn, a, b) => {
    let n = 0
    let timer = null

    const timeoutFunc = () => {
      timer ? clearTimeout(timer) : ''
      timer = setTimeout(() => {
        console.log(a+n*b, +(new Date()))
        timeoutFunc()
        fn()
        n++
      }, a + n * b);
    }

    timeoutFunc()

    return timer
  }

  const myClear = (timer) => {
    clearTimeout(timer)
  }

  const iTimer = mySetInterVal(() => console.log('zz'), 1000, 20)
  myClear(iTimer)

from fe-interview.

CYLpursuit avatar CYLpursuit commented on May 1, 2024

function mySetInterval(fn, a, b) {
let i = 0;
let timer;
function loop() {
console.log('i', i);
timer = setTimeout(() => {
fn();
i++;
loop();
}, a + i * b);
}
loop();
return timer;
},

function myClear(timer) {
  clearTimeout(timer);
},

from fe-interview.

AndSpark avatar AndSpark commented on May 1, 2024
let shut = false;
const shutDown = () => shut = true
const sleep = (time: number) => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			shut && reject()
			resolve('')
		}, time);
	})
}
const mySetInterVal = async (fn: Function, a: number, b: number) => {
	try {
		await sleep(a)
		fn()
		await sleep(a + b)
		fn()
		await sleep(a + 2 * b)
		fn()
		mySetInterVal(fn, a, b)
	} catch (error) {
		console.log('close');
	}
}
mySetInterVal(()=> console.log(123), 1000, 1500)

from fe-interview.

hahei89 avatar hahei89 commented on May 1, 2024

// 写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b,...,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterVal
function mySetInterval (fn, a, b) {
var timer
var count = 0
var canStart = true
function setIntervalFunc () {
if (canStart) {
timer = setTimeout(() => {
fn()
count += 1
setIntervalFunc()
}, a + count * b)
}
}
setIntervalFunc()
function myClear () {
canStart = false
if (timer) {
clearTimeout(timer)
}
canStart = true
}
return myClear
}

// 测试
function timerFunc () {
console.log('timer func')
}
var clear = mySetInterval(timerFunc, 300, 300)
setTimeout(() => {
clear()
}, 10000)

from fe-interview.

liangqingda avatar liangqingda commented on May 1, 2024

// 闭包方式实现:
function mySetInterval(fn, a, b) {
let count = 0;
let exe = true;
const myInterval = () => {
if (!exe) return;
setTimeout(() => {
fn();
count++;
myInterval();
}, a + (count * b));
};
return {
myInterval,
clearInterval: () => {
exe = false;
},
};
}

function myClear(interval) {
interval.clearInterval();
}

// 测试
const interval = mySetInterval(() => {console.log('执行')}, 1000, 1000);
interval.myInterval();

setTimeout(myClear.bind(null, interval), 6000);

from fe-interview.

Adermi avatar Adermi commented on May 1, 2024
function mySetInterVal(fn, a, b) {
	let timerArr = []
	let index = 1
	~(function start() {
		if (index == 0) return
		let time = a + (index++ * b)
		let i = setTimeout(() => {
			fn()
			timerArr.shift()
			start()
		}, time)
		timerArr.push(i)
	})()

	return function end() {
		index = 0;
		timerArr.forEach(item => clearTimeout(item)) // 遍历删除定时器
	}
}

let end = mySetInterVal(() => {
	console.log('我被执行了')
}, 100, 200)

setTimeout(end, 10000)

from fe-interview.

fengbujue2022 avatar fengbujue2022 commented on May 1, 2024
        const mySetInterVal = (fn: () => void, a: number, b: number) => {
            let timer: any;
            const run = (ms: number) => {
                if (timer) {
                    clearTimeout(timer)
                }
                return setTimeout(() => {
                    fn();
                    timer = run(ms + b);
                }, ms);
            }
            timer = run(a);
            return () => {
                clearTimeout(timer);
            }
        }
        const myClearer = mySetInterVal(() => console.log(new Date()), 100, 500)

from fe-interview.

raomaiping avatar raomaiping commented on May 1, 2024
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <button onclick="a.strat()">开始</button>
    <button onclick="a.stop()">结束</button>
</head>

<body>

</body>

</html>

<script>
    class mySetInterVal {
        constructor(fn, a, b) {
            this.fn = fn;
            this.a = a;
            this.b = b;
            this.index = 0;
            this.handle = null
        }

        strat() {
            this.handle = setTimeout(() => {
                this.index++;
                this.fn();
                this.strat()
                console.log(this.a, this.index, this.index * this.b);
            }, this.a + this.index * this.b)
        }
        stop() {
            this.index = 0;
            clearInterval(this.handle)
        }
    }

    function fn() {
        console.log(11);
    }
    const a = new mySetInterVal(fn, 1000, 2000)

</script>

from fe-interview.

yuxiziyoutiankong avatar yuxiziyoutiankong commented on May 1, 2024
(function(w) {
  let timer = null
  let count = 0
  function mySetInterval(fn, a, b) {
    let interval = _ => {
      timer = setTimeout( _ => {
        fn(a + count*b)
        count++
        interval(count)
      }, a + count*b)
    }
    interval()
  }
  function clearMyInterval() {
    clearTimeout(timer)
    count = 0
  }
  w.mySetInterval = mySetInterval
  w.clearMyInterval = clearMyInterval
})(window)

from fe-interview.

zhoocoo avatar zhoocoo commented on May 1, 2024
function myInterval(fn, a, b) {
  let inter = 0
  let timeoutId = null
  let stopFlag = false
  function interVal(fn) {
    timeoutId = setTimeout(() => {
      fn && fn(inter)
      if (!stopFlag) interVal(fn)
    }, a + inter++ * b)
  }
  interVal(fn)

  return () => {
    stopFlag = true
    clearTimeout(timeoutId)
  }
}

let stop = myInterval(
  (c) => {
    console.log(c)
    if (c === 4) {
      stop()
    }
  },
  1000,
  200
)

返回的停止函数中有两个清理,一个是stopFlag作为标识,一个是clearTimeout

看了下很多伙伴都只写了clearTImeout来停止,如果是在myInterval回调中想去停止,光有一个clearTImeout是不够的,因为clearTimeout仅仅可以取消还未执行的回调,即还处于延迟队列中的回调。所以内部执行完了fn && fn(inter)后,即使stop了,也同样会像延迟队列中添加一个新的setTimeout回调函数

当然只写stopFlag也可以,但是,clearTimeout可以帮助我们直接从 延迟队列中直接移除还未执行的myInterval回调函数(可能还有10秒才执行此任务),因此带上clearTimeout更加合适。

from fe-interview.

Hunterang avatar Hunterang commented on May 1, 2024

不知道行不行

function mySetInterVal(fn, a,b) {
            fn.index = fn.index? fn.index++ : 0
            
            window.timer = setTimeout(() => {
                fn()
                mySetInterVal(fn, a,b)
            }, a + fn.index*b)
        }
        function myClear() {
            clearTimeout(window.timer)
            
        }

from fe-interview.

nhyu avatar nhyu commented on May 1, 2024
const demo = {
    mySetInterVal(fn, a, b) {
        this.timer = setTimeout(() => {
            fn && fn(a);
            this.mySetInterVal(fn, a + b, b)
        }, a);
    },
    myClear() {
        clearTimeout(this.timer);
    },
}
// test
demo.mySetInterVal((interval) => { console.log(interval) }, 1000, 500);
setTimeout(() => {
    demo.myClear();
}, 5000);
// 结果分别是: 1000,1500,2000

from fe-interview.

pirtor avatar pirtor commented on May 1, 2024
// solution
function mySetInterVal(fn, a, b) {
  let timer = null;
  const interVal = (fn, a, b) => {
    timer = setTimeout(() => {
      fn();
      interVal(fn, a + b, b);
    }, a);
  };

  interVal(fn, a, b);

  // myClear
  return () => {
    clearTimeout(timer);
  };
}

// test
let last = new Date().getTime();
const myClear = mySetInterVal(
  () => {
    let curr = new Date().getTime();
    const diff = curr - last;
    console.log(diff);
    last = curr;
  },
  1000,
  500
);
setTimeout(myClear, 10000);

from fe-interview.

Power-kxLee avatar Power-kxLee commented on May 1, 2024
// 写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b 的时间,然后写一个 myClear,停止上面的 mySetInterVal
    const mySetInterVal = (fn, a, b) => {
      let i = 1
      let t
      const mySetTimeout = (i) => {
        let n = a + i*b
        t = setTimeout(() => {
          i++ 
          fn()
          mySetTimeout(i)
        }, n);
      }
      
      mySetTimeout(i)
      const myClear = () => {
        clearTimeout(t)
      }
      return {
        myClear 
      }
    }
    const _inter = mySetInterVal(()=> {
      console.log('hah')
    }, 100, 100)
    _inter.myClear()

from fe-interview.

Power-kxLee avatar Power-kxLee commented on May 1, 2024
// 写一个 mySetInterVal(fn, a, b),每次间隔 a,a+b,a+2b 的时间,然后写一个 myClear,停止上面的 mySetInterVal
    const mySetInterVal = (fn, a, b) => {
      let i = 1
      let t
      const mySetTimeout = (i) => {
        let n = a + i*b
        t = setTimeout(() => {
          i++ 
          fn()
          mySetTimeout(i)
        }, n);
      }
      
      mySetTimeout(i)
      const myClear = () => {
        clearTimeout(t)
      }
      return {
        myClear 
      }
    }
    const _inter = mySetInterVal(()=> {
      console.log('hah')
    }, 100, 100)
    _inter.myClear()

from fe-interview.

opacitySun avatar opacitySun commented on May 1, 2024
function mySetInterVal(fn, a, b){
  let ms = a;
  let timer = null;
  const loop = () => {
    timer = setTimeout(() => {
      console.log(ms);
      fn();
      ms += b;
      loop();
    }, ms);
  }
  loop();
  return () => {
    if(timer) clearTimeout(timer);
  }
}

const myFn = mySetInterVal(() => {
  console.log(1111);
}, 1000, 2000);

//清除轮询
myFn();

from fe-interview.

FliPPeDround avatar FliPPeDround commented on May 1, 2024

class MySetInterval{
private time:number
a:number
b:number
fn:Function
constructor(fn:Function, a:number, b:number) {
this.time = 0
this.a = a
this.b = b
this.fn = fn
this.start()
}

setTime(){
setTimeout(() =>{
this.fn()
this.time++
this.start()
},this.a + this.time * this.b)
}

start(){
this.setTime()
}

myclear(){
clearTimeout(this.setTime as unknown as NodeJS.Timeout)
this.time = 0
}
}

const foo = new MySetInterval(() => console.log(123), 1000, 1000)
foo.myclear()

from fe-interview.

zizxzy avatar zizxzy commented on May 1, 2024
function myInterval(fn, a, b) {
    let timeCount = 0;
    let timer = null;
    const loopFunction = () => {
        timer = setTimeout(() => {
            fn();
            timeCount++;
            loopFunction();
        }, a + timeCount * b)
    }
    loopFunction();
    return function () {
        clearTimeout(timer);
    }
}

const myclear = myInterval(() => { console.log('fn') }, 500, 500);
myclear();

from fe-interview.

roy2an avatar roy2an commented on May 1, 2024
function mySetInterVal(fn, a, b) {
    const o = {}
    function t() {
        o.h = setTimeout(()=> {
            fn()
            t()
            console.log( a+b);
            a+= b
        }, a + b)
        // console.log(a + b)
    }
    t()
    return () => {
        clearTimeout(o.h)
    }
}
var myClear = mySetInterVal(() => {console.log('123')},1000, 2000 );
setTimeout(() => {myClear()}, 8000)

from fe-interview.

zhaoxm469 avatar zhaoxm469 commented on May 1, 2024

let timer = 0;

const myClear = () => clearInterval(timer);

const mySetinterVal = (fn, a,b) =>{
let index = 0 ;
(function start(wait){
timer = setTimeout(() => {
fn();
index++;
console.log(wait)
clearInterval(timer)
start(a + index*b);
}, wait);
})(a);
}

mySetinterVal(()=>{
console.log(1)
},1000,2000)

from fe-interview.

chihaoduodongxi avatar chihaoduodongxi commented on May 1, 2024

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();

from fe-interview.

avenir-zhang avatar avenir-zhang commented on May 1, 2024
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))
  }
}

from fe-interview.

wmlgl avatar wmlgl commented on May 1, 2024
    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);

from fe-interview.

lang711 avatar lang711 commented on May 1, 2024
    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)

from fe-interview.

huanmiezhicheng avatar huanmiezhicheng commented on May 1, 2024

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()

from fe-interview.

captain-kuan avatar captain-kuan commented on May 1, 2024
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)

from fe-interview.

Charles-ShiZ avatar Charles-ShiZ commented on May 1, 2024
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)

from fe-interview.

ResidualStar avatar ResidualStar commented on May 1, 2024

image

from fe-interview.

drlsxs avatar drlsxs commented on May 1, 2024
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);

from fe-interview.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.