There are several issues to address.
When using hide_info
, it is important to note that it is invoked immediately. Remember, parentheses are not just for grouping expressions but also for invoking function-objects!
In the case of:
this.id = setTimeout(this.hide_info(), 7000);
It can be misunderstood as:
var temp = this.hide_info() // calling a function...wait, what?
this.id = setTimeout(temp, 7000) // temp returns "undefined" here
Oops! That's incorrect. To avoid this mistake, remove the parentheses. By doing so, the actual function-object will be passed to setTimeout
. (Yes, functions in JavaScript are treated as objects. The expression this.hide_info
is evaluated first to become a function-object, and if followed by (...)
, it will trigger the function-object.)
this.id = setTimeout(this.hide_info, 7000)
However, this still poses an issue because within the timeout function (hide_info
), this
will refer to the wrong context. This can be resolved by implementing a closure. (Numerous valuable explanations on this topic exist on platforms like Stack Overflow; feel free to explore!)
var self = this
this.id = setTimeout(function () {
// now inside hide_info, "this" refers to "self", which was originally "this" outside :)
self.hide_info()
}, 7000)
(Alternatively, consider using Function.bind
from ECMAScript ed5 or a suitable library.)
Furthermore, it's worth noting that this.id
does not equate to this.timeoutID
and should be validated for correctness.
Simplicity is key. It's perfectly acceptable to pass undefined or zero to clearTimeout; the method will simply disregard such inputs.
cancel: function () {
clearTimeout(this.id) // though "id" may be a confusing naming choice :)
this.id = undefined
}
Wishing you success in your coding endeavors.