如何在我的情况下创建计时器?

时间:2014-01-31 03:35:12

标签: javascript jquery css

我想让我的按钮做两件事。

初始化一个定时器来调用一个函数 调用相同的函数

我有类似以下的内容

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秒钟之前再次点击按钮,他们也可以看到内容。我不确定如何通过一次点击事件来区分这两种不同的状态。谁能帮我吗?谢谢!

1 个答案:

答案 0 :(得分: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
}
相关问题