Constantly check the length of an element and perform an action if it is ever 1

257 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

You can use a mutation observer on a parent/ancestor node instead, watching for changes to the subtree and/or childList.

var ancestor = $("...closest ancestor that doesn't change..."); // Worst case, $('body')
var ob = new MutationObserver(function() {
    if($('.username_field').length == 1){
        loginUser();
    }
});
ob.observe(ancestor[0], {
    subtree: true,   // You probably only need...
    childList: true  // ...one of these or the other
});

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.