实现setInterval
思路:递归
function imitateSetInterval (func, milliseconds, count) {
var temp = [count];
function interval () {
if (typeof count === 'undefined' || temp[0] -- > 0) {
setTimeout(interval, milliseconds);
try {
func();
}catch (e) {
throw e.toString();
}
}
}
setTimeout(interval, milliseconds);
return temp;
}
实现clearInterval
思路:改变imitateSetInterval返回的引用
function imitateClearInterval (temp) {
temp[0] = 0;
}
使用
var i = 0;
var terval = imitateSetInterval(function () {
console.log(i++);
}, 1000, 100)
imitateClearInterval(terval)