题目
写一个 mySetInterval(fn, a, b),每次间隔 a,a+b,a+2b,...,a+nb 的时间,然后写一个 myClear,停止上面的 mySetInterval
标签
js 字节跳动
知识点
- 作用域
- 引用类型
- 定时器
- 递归
- code style
题解
常规
// 启动计时执行
function mySetInterval(fn, a, b) {
let n = 0,
tag = {
timer: 0
}
function innter() {
tag.timer = window.setTimeout(() => {
fn()
console.log(a, b, n,a + n * b)
++n
innter()
}, a + n * b)
}
innter()
return tag
}
// 清除计时执行
function myClear(tag) {
window.clearTimeout(tag.timer)
}
oop + es6
class MySetInterval {
constructor(fn, a, b) {
this.fn = fn
this.a = a
this.b = b
this.n = 0
this.timer = 0
}
start() {
// 此处省略校验...
this.timer = window.setTimeout(() => {
this.fn()
this.n++
this.start()
console.log(this.a, this.n, this.b, this.a + this.n * this.b)
}, this.a + this.n * this.b)
}
stop() {
window.clearTimeout(this.timer)
}
}
// var mySetInterval = new MySetInterval(() => {console.log(Date.now())}, 1000, 1000 )
// mySetInterval.start()
// mySetInterval.stop()
其他思路(比如: TS写法),请自行研习。
更多精彩面试题分析,请扫码关注 「乘风破浪大前端」。还可以回复: "面试题", 获取10+经典面试题资料哦!
See you, next time ~
本文使用 mdnice 排版