2014-01-31 36 views
1

我想讓我的按鈕做兩件事。如何在我的情況下創建計時器?

初始化一個計時器來調用一個函數 調用同一個函數

我有類似如下的

test.prototype.setupEvent= function(){ 
     var instance = this; 

     $('#btn').on('click', function(){ 
      clearInterval(instance.timer); 
      this.showStuff() 

      instance.timer=setInterval(function(){ 
       instance.showStuff() 
      },10000); 
     }) 
    } 

test.prototype.showStuff= function(btnID){ 
     //jump to another page 
    } 

我的問題是,我希望用戶能夠看到後10秒一些內容當他們第一次點擊它時,如果他們在10秒鐘之前再次點擊該按鈕,他們也可以看到內容。我不知道如何通過單擊事件來區分兩種不同的狀態。誰能幫我嗎?謝謝!

+0

「初始化定時器來調用一個函數調用相同的功能」 - 請重寫這個部分,我不知道你是什麼意思 – JLewkovich

+0

您可以編輯[這個小提琴(HTTP: //jsfiddle.net/arunpjohny/yf5XM/1/)來創建案例 –

回答

1

嘗試

test.prototype.setupEvent = function() { 
    var instance = this; 

    $('#btn').on('click', function() { 
     //if there is a timer running then clear the timer, show the content and delete the timer reference 
     if (instance.timer) { 
      clearInterval(instance.timer); 
      instance.showStuff(); 
      delete instance.timer 
      return; 
     } 
     //also you may want to use setTimeout() not setInverval() 
     instance.timer = setInterval(function() { 
      instance.showStuff(); 
      delete instance.timer 
     }, 10000); 
    }) 
} 

test.prototype.showStuff = function (btnID) { 
    //jump to another page 
} 
相關問題