Skip to content

Instantly share code, notes, and snippets.

@Teemwu
Last active September 14, 2021 10:06
Show Gist options
  • Save Teemwu/48fe604c10c525dcf33e24911150d20d to your computer and use it in GitHub Desktop.
Save Teemwu/48fe604c10c525dcf33e24911150d20d to your computer and use it in GitHub Desktop.
setTimeout 模拟实现 setInterval
'use strict';
/**
* 使用 setTimeout 模拟 setInterval
* @param {Function|string} handler 要执行的函数或者要执行的函数字符串
* @param {number} delay 时间间隔
*/
window._setInterval = function (handler, delay) {
// 判断第二个参数是否为字符串
const isFunc = typeof handler === 'string'
// 获取第二个参数后的其它参数
const args = Array.prototype.slice.call(arguments, 2)
const timer = function () {
setTimeout(
function () {
isFunc ? eval(handler) : handler(...arguments)
timer()
},
delay,
...args
)
}
timer()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment