2013-04-24 91 views
0

我一直在試圖解決如何做到這一點,並沒有真正得到任何地方。點擊按鈕時,我需要暫停下面的功能,再次點擊時再次啓動它。單擊按鈕時暫時暫停功能

var About = function(dom) { 
    this.text_spans = $('li', dom); 
    this.len = this.text_spans.length; 
    this.index = 0; 

    this.init(); 

} 

$.extend(About.prototype, { 
    interval: 2.5 * 1000, 
    init: function() { 
     var that = this; 
     setTimeout(function() { 
      that.text_spans.eq(that.index++ % that.len).removeClass('visible'); 
       that.text_spans.eq(that.index % that.len).addClass('visible'); 
      setTimeout(arguments.callee, that.interval); 
     }, that.interval); 
    } 
}); 

此功能的目的是隱藏的一系列文本(例如,在li「S)和與環回圓形無限。點擊按鈕/鏈接時,該功能將暫停並停止更改文本。

我知道這與setTimeout()和clearTimeout()有關,但我並不真正瞭解使其工作的語法或方法。任何人都可以幫助我理解它嗎?非常感謝你:)

+0

能否請您分享的jsfiddle演示,它將使我們更容易幫助你:) – Mottie 2013-04-24 22:01:20

+0

當然,對不起,我忘了。以下是鏈接:http://jsfiddle.net/Xb5Xg/1/ – 2013-04-24 22:08:54

回答

0

嘗試這樣的事情(demo):

$.extend(About.prototype, { 
    interval: 2.5 * 1000, 
    init: function() { 
     var that = this; 
     $('a.toggle').click(function(){ 
      var running = $(this).hasClass('running'); 
      $(this).toggleClass('running', !running); 
      if (running){ 
       clearInterval(that.timer); 
      } else { 
       that.timer = setInterval(function() { 
        that.text_spans.eq(that.index++ % that.len).removeClass('visible'); 
        that.text_spans.eq(that.index % that.len).addClass('visible'); 
       }, that.interval); 
      } 
     }).click(); // start timer 
    } 
}); 

HTML

<a class="toggle" href="#">Click me to pause function</a>