欢迎在下方发表您的优质见解
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();
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);
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);
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()
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)
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();
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);
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);
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)
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);
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)
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 )
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)
// 第 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();
题目不太清晰啊,是每次间隔以此类推吧
题目不太清晰啊,是每次间隔以此类推吧
@Marckon
是有点,改了,感谢提出问题
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)
}
// 没有人比我的代码更短!
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()
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)
// code by [email protected]
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)
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)
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);
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();
}
借鉴前面的思路,通过对象传递的是引用的特性,获取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);
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);
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);
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);
};
}
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)
// 没有人比我的代码更短! 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);
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();
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);
```javascript
/**
mySetInterVal((a, count, b) => console.log(a: ${a} count: ${count} b: ${b} ${a}+${count}*${b}: ${a + count * b}), 1000, 2000);
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)
}
}
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()) })
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);
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();
将 start 和 stop 函数在构造函数中初始化不太好,显得很臃肿,而且完全没有必要使用面向对象的方法解答
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();
}
```js
// 没有人比我的代码更短!
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);
和我的想法一样,哈哈。
为了保持和原生 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);
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();
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
);
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);
我感觉这个挺好的,比较容易理解
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)
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();
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);
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后会强制取消'`
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)
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)
// 没有人比我的代码更短! 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);
Most helpful comment