保持用户会话活着的问题

Mik*_*den 3 javascript settimeout

我有一个想法是通过发送webservice调用来保持用户的会话活动,设置超时一段时间(比如15分钟左右)然后回想一下相同的方法.

问题是网络服务似乎不断发生.不像我想的那样每隔15分钟.

链接可以在这里找到:小提琴

代码在这里:

(function($, window, document, undefined) {
    "use strict";

    var methods, 
        settings,
        timeout,
        type = 'sessionPing';

    methods = {
        init: function () { 
            settings = { time: 5000};

            methods.request.call(this);
        },

        request: function () { 
            console.log('just before clear' + timeout);
          clearTimeout(timeout);

            $.ajax({ type: 'POST',
                   url: '/echo/html/',
                   data: {
                    'html': 'Echo!'
                   },
                   success: function(data) {
                     timeout = setTimeout(methods.request(), settings.time);  
                       console.log('in success ' + timeout);
                   },
                   dataType: 'html'
                });  
        }
    };

    $.sessionPing = function(method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.timeSince');
        }
    };

}(jQuery, window, document));


$(function() {
    $.sessionPing();
});    
Run Code Online (Sandbox Code Playgroud)

ajm*_*ajm 7

timeout = setTimeout(methods.request(), settings.time);
Run Code Online (Sandbox Code Playgroud)

那里的括号将自动运行methods.request,而后者将运行自动运行的代码methods.request; 基本上,该方法将一遍又一遍地执行,将自身的越来越多的版本绑定到您的间隔.

timeout = setTimeout(methods.request, settings.time);
Run Code Online (Sandbox Code Playgroud)

这就是你要找的东西:只是传递函数签名而不是传递一个作为副作用执行的函数.


Nea*_*eal 5

修复超时,使其调用函数:

timeout = setTimeout(function(){methods.request()}, settings.time); 
Run Code Online (Sandbox Code Playgroud)

如果你不这样做,那么你的功能已经放置在超时将被立即调用.