getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2019
getButterfly

Search for an element until found using JavaScript

A nice piece of code to use for A/B testing to look for a certain element every 50 milliseconds, execute the code when found, then clear the interval loop. If the element is not found the loop is interrupted after 15 seconds.

var ytTimeoutId;

window.onload = function() {
    ytTimeoutId = setInterval(function() {
        // Check for a specific element ID
        if (document.getElementById('element')) {
            // Do stuff

            window.clearInterval(ytTimeoutId);
        }
    }, 50);

    setTimeout(function() {
        window.clearInterval(ytTimeoutId);
    }, 15000);
}

Change the interval ping value or the general timeout value (15 seconds) as you see fit.

Find more JavaScript tutorials, code snippets and samples here.

Added by Ciprian on Tuesday, September 19, 2017 in Blog

Do you want better SEO? More traffic? More conversions? More growth? We help companies exponentially grow their traffic and conversions, while outranking their competitors. With more than 10 years of experience, we’ve learned what is valuable to our clients.
SEO Dublin | SEO Malta

My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.


Privacy Policy