Last active
September 14, 2021 10:06
-
-
Save Teemwu/48fe604c10c525dcf33e24911150d20d to your computer and use it in GitHub Desktop.
setTimeout 模拟实现 setInterval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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