Last active
August 29, 2015 14:06
-
-
Save agamemnus/167c52c2a795e4db7c36 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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