I\'ve got some code that I want to run when certain HTML elements are added to t
ID: 646646 • Letter: I
Question
I've got some code that I want to run when certain HTML elements are added to the page.
To do this, I have a "runOnRender" function:
runOnRender: function (func, args, interval) {
var that = this;
var guid = hb.getGuid().substr(0,7);
var checkFunc = function () {
if (that.$el.height() > 0 && that.$el.width() > 0) {
clearInterval(that[guid]);
that[guid] = 0;
func.call(that, args);
}
};
this[guid] = setInterval(checkFunc, interval || 200);
}
Setting the interval to 200 is about as high as I can go before there is often a noticeable lag in the event firing. The last thing I want is my users wondering why a button just got clicked or seeing a label text change, etc.
Here's the catch. It is entirely possible that this "runOnRender" will be set up.....but the User never causes the action that makes the HTML element in question hit the DOM....which means that this code would just keep infinitely running as long as the page is open.
I'm on a nice, powerful, dev machine....so I'm wondering what the cost of this code is and whether there is a better way.
Explanation / Answer
Mostly, don't worry about it, you can run something like several million light lines of code per second. If you spend a few thousand of those doing some check, no worries. The overhead of the interval construction itself should be negligible.
If you want to be sure, put in a loop that runs the body of checkFunc 100 times, check with task manager how much CPU that eats, and verify that the page is still responsive. If that checks out good even a dated smart phone should do the normal job handily.
It is also worth noting that most modern browsers will slow script execution on inactive tabs by only letting them execute code something like once per second, so as soon as the tab is inactive it doesn't matter if you ask for once per 20 or 200 ms, you only get once per 1000 ms anyway, and intervals do not catch up.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.