Skip to content

Instantly share code, notes, and snippets.

@agamemnus
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agamemnus/167c52c2a795e4db7c36 to your computer and use it in GitHub Desktop.
Save agamemnus/167c52c2a795e4db7c36 to your computer and use it in GitHub Desktop.
// Add a setTimeout and setInterval to HTMLElement. The setTimeout and setInterval remove themselves if the element is removed.
// Another possible implementation: global service.
HTMLElement.prototype.setTimeout = function (callback, calltime) {
var current_element = this
function is_attached (obj) {
while (true) {
obj = obj.parentNode
if (obj == document.documentElement) return true
if (obj == null) return false
}
}
function callback_wrapper () {
var args = Array.prototype.slice.call (arguments)
if (!is_attached(current_element)) return
callback.apply (null, args)
}
var timeout_id = window.setTimeout (callback_wrapper, calltime)
return timeout_id
}
HTMLElement.prototype.setInterval = function (callback, calltime) {
var current_element = this
function is_attached (obj) {
while (true) {
obj = obj.parentNode
if (obj == document.documentElement) return true
if (obj == null) return false
}
}
function callback_wrapper () {
var args = Array.prototype.slice.call (arguments)
if (!is_attached(current_element)) {clearInterval (interval_id); return}
callback.apply (null, args)
}
var interval_id = window.setInterval (callback_wrapper, calltime)
return interval_id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment