用setTimeout模拟setInterval的功能

偶然看到这个题目,稍微写了下,做个笔记,不足之处请指正

//用setTimeout模仿setInterval
var MyInterVal = function(fun,tm){
    if(this == window){
        return new MyInterVal(fun,tm);
    }
  this.Fun = null;
this.id = -1;this.clear = function(id){ clearTimeout(this.id); } this.setInterval = function(_fun,_tm){ var self = this; if(this.Fun==null){ if(typeof _fun=="string"){ this.Fun = new Function(_fun); }else if(typeof _fun=='function'){ this.Fun = _fun; } } this.id = setTimeout(function(){ self.Fun(); self.setInterval(self.Fun,_tm); },tm); } this.setInterval(fun,tm); } //使用方法一 var s = MyInterVal(function(){ console.log(1); },1000); //使用方法二 var s = MyInterVal("console.log(1)",1000) setTimeout(function(){ s.clear();//清除 },5000)
原文地址:https://www.cnblogs.com/laojun/p/8528832.html