setTimeout - 立即执行回调? [英] setTimeout -- callback executed immediately?

查看:263
本文介绍了setTimeout - 立即执行回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让一个元素淡入,并在页面淡出前停留在页面上7秒钟。我可以随时取消它。
我定义了以下函数。但当我打电话给 info_timeout.setup(ele,'some msg here')时,电子元素刚刚消失并立即淡出。

I want to let an element fade in, and stay on the page for 7 seconds before it fades out. And I can cancel it anytime. I defined the following functions. But when I called info_timeout.setup(ele, 'some msg here'), the ele just faded in and faded out immediately.

我错过了什么吗?

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;
    }
}

};

谢谢。

推荐答案

有几个问题。

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

This invokes hide_info right away. Parenthesis invoke a function-object! (or are used for applying precedence to expressions).

即,

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 首先评估到函数对象,如果有(...)之后,它将调用所述函数对象。)

Oops! That's not right :) So take away the parenthesis. This will pass the function-object itself to the setTimeout. (Yes, functions are just objects in JavaScript. The expression this.hide_info is first evaluated to a function-object and, if there is a (...) after, it will invoke said function-object.)

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

然而,它是仍然不正确,因为这个在超时功能( hide_info )里面会出错!但是这可以通过使用闭包来解决。 (关于这个主题有很多很棒的答案,请随时搜索!)

However, it is still not correct because this inside the timeout function (hide_info) will be wrong! But this can be fixed with using a closure. (There are many great SO answers on the topic, feel free to search!)

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

(或使用 Function.bind 来自ECMAScript ed5或库。)

(Or use Function.bind from ECMAScript ed5 or a library.)

此外, this.id this.timeoutID ,并且怀疑正确。

Additionally, this.id is not the same as this.timeoutID, and is suspect for "correctness".

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

Keep it simple. It's okay to pass undefined/0 to clearTimeout: it'll silently ignore you.

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

快乐编码。

这篇关于setTimeout - 立即执行回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆