Jen*_*sen 1 javascript timeout clear settimeout
我想让一个元素淡入,并在它消失之前在页面上停留7秒.我可以随时取消它.我定义了以下功能.但是当我打电话时info_timeout.setup(ele, 'some msg here')
,电子元件刚刚消失并立即消失.
我错过了什么吗?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
};
谢谢.
小智 5
几个问题.
这将调用hide_info
的时候了.括号调用函数对象!(或用于对表达式应用优先级).
那是,
this.id = setTimeout(this.hide_info(), 7000);
Run Code Online (Sandbox Code Playgroud)
[大部分]相当于:
var temp = this.hide_info() // call function ... uh, what?
this.id = setTimeout(temp, 7000) // temp is "return" value ("undefined" here)
Run Code Online (Sandbox Code Playgroud)
哎呀!那不对:)所以拿掉括号.这会将函数对象本身传递给setTimeout
.(是的,函数只是JavaScript中的对象.表达式this.hide_info
首先被计算为一个函数对象,如果有一个(...)
after,它将调用所述函数对象.)
this.id = setTimeout(this.hide_info, 7000)
Run Code Online (Sandbox Code Playgroud)
但是,它仍然不正确,因为this
在超时函数(hide_info
)内部将是错误的!但是这可以通过使用闭包来解决.(关于这个主题有很多很棒的答案,请随时搜索!)
var self = this
this.id = setTimeout(function () {
// now in hide_info "this" will be "self", which was "this" ... outside :)
self.hide_info()
}, 7000)
Run Code Online (Sandbox Code Playgroud)
(或者使用Function.bind
ECMAScript ed5或库.)
另外,与"正确性" this.id
不一样this.timeoutID
,并且怀疑它是否正确.
把事情简单化.将undefined/0传递给clearTimeout是可以的:它会默默地忽略你.
cancel : function () {
clearTimeout(this.id) // but id is a horrid overloaded name :)
this.id = undefined
}
Run Code Online (Sandbox Code Playgroud)
快乐的编码.