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

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

 

相关文章:

  • 2021-07-27
  • 2021-12-03
  • 2021-11-13
  • 2021-06-16
  • 2021-07-09
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-03-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-13
相关资源
相似解决方案