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);
    }
});

此函数的目标是隐藏一系列文本(例如,in li's)并无限循环返回。单击按钮/链接时,该功能将暂停并停止更改文本。

我知道这setTimeout()与 clearTimeout() 有关,但我并不真正了解使其工作的语法或方法。谁能帮我理解它?非常感谢 :)

4

1 回答 1

0

尝试这样的事情(演示):

$.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>
于 2013-04-24T22:28:18.823 回答