2016-01-11 38 views
1

的js小提琴:check here的setInterval工作不正常使用javascript哎呀

我的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); 

回答

7

thi = this;在全局命名空間創建,所以被每次初始化一個new timer()時間覆蓋。

將其更改爲var thi = this;

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

我不喜歡thi的變數名稱 - 它看起來像一個錯字。我通常使用_this_scope

+0

謝謝,這有效.. –

+1

看你的小提問題對我來說更有意義.....; – Jai

+0

你是什麼意思@Jii? –

0

試試這個:

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需要在本地聲明和感動。