【问题标题】:setInterval not working as expected with javascript oopsjavascript oops 的 setInterval 无法按预期工作
【发布时间】:2016-01-11 09:16:57
【问题描述】:

Js 小提琴:check here

我在一个类的方法中设置了 setInterval()。创建单个实例时它可以正常工作,但创建多个实例时它会失败。当创建多个实例时,只有最后一个创建的实例起作用,其他的停止。

我的脚本如下:

function timer() {
    this.ran = Math.floor(Math.random() * 100) + 1;
    this.cls = this.ran + '_ocar';
    this.div = '<div class="' + this.cls + '">' + this.cls + '</div>';
    $('body').append(this.div);
    this.run = function() {
        thi = this;
        thi.k = 0;
        setInterval(function() {
            console.log(thi.cls);
            $('.' + thi.cls).html(thi.k++);
        }, 1000);
    }
}
one = new timer();
one.run();
setInterval(function() {
    new timer().run();
}, 5000);

【问题讨论】:

    标签: javascript jquery oop setinterval


    【解决方案1】:

    thi = this; 正在全局命名空间中创建,因此每次初始化 new timer() 时都会被覆盖。

    将其更改为var thi = this;

    https://jsfiddle.net/daveSalomon/h5e8LLg3/`

    我不喜欢 thi 作为 var 名称 - 它看起来像是一个错字。我通常使用_this_scope

    【讨论】:

    • @ Jai 是什么意思?
    【解决方案2】:

    试试这个:

     function timer(){
        var thi = this;
        this.ran = Math.floor(Math.random() * 100) + 1;
        this.cls =  this.ran+'_ocar';
        this.div = '<div class="'+this.cls+'">'+this.cls+'</div>';
        $('body').append(this.div);
        this.run = function(){
    
           thi.k = 0;
           setInterval(function(){
             console.log(thi.cls);
             $('.'+thi.cls).html(thi.k++);
          },1000);
       }
    }
    one = new timer();
    one.run();
    setInterval(function(){
      new timer().run();
    },5000)
    

    您的变量thi 需要在本地声明并移动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2016-10-01
      相关资源
      最近更新 更多