【问题标题】:jQuery - 3 minutes in secondsjQuery - 以秒为单位的 3 分钟
【发布时间】:2024-01-14 08:16:01
【问题描述】:

我认为这很容易,但似乎我要么做空要么做多。

我试图让它在 3 分钟后让用户退出 这是我认为会工作的倒计时我已经尝试过 3000、300、3*60、3*1000 等等

var timeout = 30*1800;

这是我要运行的函数,

    function loadidle(){

          var timeout = 180000;
          //alert(timeout);

          $(document).bind("idle.idleTimer", function(){

              logout();

          });


          $.idleTimer(timeout);
}

【问题讨论】:

  • 1000*60*3(1000 毫秒,乘以 60 秒,乘以 3 分钟)

标签: jquery timer timeout seconds minute


【解决方案1】:

您只需要一个简单的计时器。有很多品种。这是一个非常便宜的示例,它很好地将其抽象为一个类。您可以通过调用 .reset() 来“继续”计时器。

function Timeout(seconds, callback){
    this.length = seconds * 1000;
    this.callback = callback;
    this.start();
}
Timeout.prototype = {
    start: function(){
        var self = this;
        this.stop();
        this.timer = setTimeout(function(){
            self.complete();
        },this.length);
    },
    stop: function(){
        if (this.timer) clearTimeout(this.timer);
        this.timer = null;
    },
    complete: function(){
        if (this.callback) this.callback();
        this.stop();
    },
    reset: function() {
        this.stop();
        this.start();
    }
}

开始一个新的计时器:

var timer = new Timeout(3 * 60, logout);
timer.reset(); // refresh the timer
timer.stop(); // cancel the timer

【讨论】:

    【解决方案2】:

    相当肯定 JS(以及因此 jQuery)使用毫秒,所以你会想要 3*60*1000。

    【讨论】:

    • 当我这样做时,使用“秒”和“分钟”作为标签并不是真正的最佳实践!