IE 9上的setTimeout()问题

时间:2013-02-05 10:08:11

标签: javascript object internet-explorer-9 settimeout

我有一个简单的js结构:

var Waiting = (function () {

    function Waiting() {
        this.timer;
    }

    Waiting.prototype.show = function () {
        var self = this;

        clearTimeout( self.timer );
        self.timer = setTimeout( function(){ self.hideLogo(); },3000);
    }

     Waiting.prototype.hideLogo = function () {
         console.log("ok i passed timeout");
     };

     return Waiting;
})();

正如预期的那样,我第一次执行show函数(称为hideLogo)时,每次浏览器都会显示“ok i pass timeout”。当我第二次调用show函数时,问题出现在IE9中。这次,从不调用hideLogo函数(日志永远不会出现在IE控制台中)。我尝试了很多事情但没有取得任何成功。

如果有人作为一个想法...

3 个答案:

答案 0 :(得分:2)

当您使用setTimeout时,正在调用的函数会丢失上下文:换句话说,this不会发布到该方法的实例上被称为了。您正在使用self取消此问题,但self本身就是 iffy 字(如保留关键字)。也许使用that,并在setTimeout调用中使用IIFE:

this.timer = setTimeout((function (that)
{
    return function()
    {
        clearTimeout(that.timer);//perhaps clear timeout here?
        that.hideLogo.apply(that,[]);//double dutch, the apply _shouldn't_ be required
    };
}(this)), 3000);

乍一看,这是我能看到的唯一可能是您的代码问题:clearTimeout调用应该不是问题,但我喜欢在超时本身结束时调用它,以及self含糊不清的事情。如果这对你有任何改变,请告诉我!

答案 1 :(得分:0)

我不确定你第二次使用提供的代码打电话给你怎么样,也许你创建一个新的等待()?

这适用于IE8

var Waiting=(function () {

    function Waiting() {
        this.timer;
    }

    Waiting.prototype.show = function () {
        var self = this;
        console.log("will clear pref timeout");
        clearTimeout( self.timer );
        self.timer = setTimeout( 
          function(){ 
            self.hideLogo(); 
           },30);
    }

     Waiting.prototype.hideLogo = function () {
         console.log("ok i passed timeout");
     };
     return new Waiting();
})();
// shows only one time
Waiting.show();
Waiting.show();
// next one will show because it lets the prefious one
// finish without clearing the pref timeout.
setTimeout(function(){
Waiting.show();
},1000);

答案 2 :(得分:0)

尝试:

setTimeout( function(){
    clearTimeout( that.timer );
    that.hideLogo();
},3000);

在IE和Chrome上为我工作。 IE在所有方面都非常落后。

相关问题