【问题标题】:setTimeout -- callback executed immediately? [duplicate]setTimeout -- 回调立即执行? [复制]
【发布时间】:2011-12-11 06:40:21
【问题描述】:

我想让一个元素淡入,并在页面上停留 7 秒,然后淡出。我可以随时取消它。 我定义了以下功能。但是当我打电话给info_timeout.setup(ele, 'some msg here')时,ele只是淡入并立即淡出。

我错过了什么吗?

var info_timeout = {
show_info: function(){
    this.ele.html(this.msg).fadeIn('normal');
    this.id = setTimeout(this.hide_info(), 7000);
},
hide_info: function(){
    console.log(this.ele, this.id);
    this.ele.fadeOut('slow');
    delete this.id;
},
setup: function(ele, msg) {
    this.ele = ele;
    this.msg = msg;
    this.cancel();
    this.show_info();
},
cancel: function() {
    if(typeof this.timeoutID == "number") {
        clearTimeout(this.id);
        delete this.id;
    }
}

};

谢谢。

【问题讨论】:

标签: javascript timeout settimeout


【解决方案1】:

几个问题。

这会立即调用hide_info括号调用函数对象!(或用于将优先级应用于表达式)。

也就是说,

this.id = setTimeout(this.hide_info(), 7000);

[大部分]等同于:

var temp = this.hide_info()       // call function ... uh, what?
this.id = setTimeout(temp, 7000)  // temp is "return" value ("undefined" here)

哎呀!这是不对的 :) 所以去掉括号。这会将函数对象本身传递给setTimeout。 (是的,函数只是 JavaScript 中的对象。表达式 this.hide_info 首先求值为函数对象,如果之后有 (...),它将调用所述函数对象。)

this.id = setTimeout(this.hide_info, 7000)

但是,仍然不正确,因为超时函数中的this (hide_info) 会出错!但这可以通过使用闭包来解决。 (关于这个主题有很多很棒的 SO 答案,请随意搜索!)

var self = this
this.id = setTimeout(function () {
    // now in hide_info "this" will be "self", which was "this" ... outside :)
    self.hide_info()
}, 7000) 

(或使用 ECMAScript ed5 或库中的 Function.bind。)

此外,this.idthis.timeoutID 不同,并且怀疑“正确性”。

保持简单。可以将 undefined/0 传递给 clearTimeout:它会默默地忽略你。

cancel : function () {
    clearTimeout(this.id)  // but id is a horrid overloaded name :)
    this.id = undefined
}

编码愉快。

【讨论】:

  • 非常感谢。欣赏它。刚开始玩js,MDN上的文档没有解释那么多。
  • 非常感谢。欣赏解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
相关资源
最近更新 更多