太上老俊

用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)

 

posted on 2018-03-08 15:40  太上老俊  阅读(979)  评论(0编辑  收藏  举报

导航