How do I pass context into setTimeout? I want to call this.tip.destroy() if this.options.destroyOnHide after 1000 ms. How can I do that?
if (this.options.destroyOnHide) {
setTimeout(function() { this.tip.destroy() }, 1000);
}
When I try the above, this refers to the window.
EDIT: In summary, back in 2010 when this question was asked the most common way to solve this problem was to save a reference to the context where the
setTimeoutfunction call is made, becausesetTimeoutexecutes the function withthispointing to the global object:In the ES5 spec, just released a year before that time, it introduced the
bindmethod, this wasn’t suggested in the original answer because it wasn’t yet widely supported and you needed polyfills to use it but now it’s everywhere:The
bindfunction creates a new function with thethisvalue pre-filled.Now in modern JS, this is exactly the problem arrow functions solve in ES6:
Arrow functions do not have a
thisvalue of its own, when you access it, you are accessing thethisvalue of the enclosing lexical scope.HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:
See also: