I have an element on a page that I am constantly monitoring. If at any time that length is equal to 1, it means it exists on the page (the user has logged out) and I want to prompt them with a popup to login.
So at the moment I have this:
function loginNotice() {
//do prompt
}
keepAlive();
function keepAlive() {
if($('.username_field').length == 1){
loginUser();
}
try {
setTimeout(function(){keepAlive();}, 10000);
} catch (ex){
}
}
I don't think this is very efficient. As it checks every so often and runs the prompt if need be. The thing is the page may load and the length may be 1 already, or it may be 0. I don't know what it will be at any given time so I can't just do an on change.
Is there a way I can do this more efficiently?
You can use a mutation observer on a parent/ancestor node instead, watching for changes to the
subtree
and/orchildList
.Having said that, though, doing a DOM query every 10 seconds isn't a problem at all; if you don't need faster reactions than that, your current solution is fine.