javascript - 如何在我的案例中创建计时器?

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

最佳答案

尝试

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
}

关于javascript - 如何在我的案例中创建计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21471957/

相关文章:

javascript - jquery背景颜色在滚动时淡入

javascript - 固定标题视差滚动

javascript - 在 Chrome 的 DevTools 中检测泄漏的 DOM 节点

javascript - 如何显示(或调用)在 javascript 数组内部定义的匿名函数的内容

javascript - 打印 JSON 对象数据时控制台上出现未定义消息

javascript - 多个图像 slider 加载图像错误

javascript - AJAX 验证改进

javascript - 找不到 Phonegap.js

javascript - 加载时不显示完整日历(带主干)

javascript - 根据变量使背景半彩色