Search code examples
javascriptfunctionlocalexecute

Execute a local function only once in pure JavaScript?


This seems so easy, but I couldn't find a proper solution yet.

What the JS does: check an element's CSS style immediately and if max-width is 1000px, do something (see JS comment). And in case the JS is executed before the CSS is applied, check again after the document has finished loading. But "do something" should only happen once, so if it was done right away, don't do it again via the event listener.

But how to avoid that? It would be easy using a global variable or function, but I want to keep those local.

(function()
{
    function checkCSS()
    {
        if (window.getComputedStyle(element).getPropertyValue('max-width') == '1000px')
        {
            // do something, but only once!
        }
    }
    checkCSS();
    window.addEventListener('load', function() {checkCSS();});
})();

Solution

  • You can remove the handler when you've done the "something," see comments:

    (function() {
        function checkCSS() {
            if (window.getComputedStyle(element).getPropertyValue("max-width") === "1000px") {
                // do something, but only once!
                // *** Remove the listener
                window.removeEventListener("load", checkCSS);
            }
        }
    
        // *** Add the listener
        window.addEventListener("load", checkCSS); // <== Note using the function directly
        // *** Do the initial check
        checkCSS();
    })();
    

    Or only add it if you didn't do "something":

    (function() {
        function checkCSS() {
            if (window.getComputedStyle(element).getPropertyValue("max-width") === "1000px") {
                // do something, but only once!
                // *** We did it (you could remove the listener here, but it doesn't really matter)
                return true;
            } else {
                // *** Didn't do it
                return false;
            }
        }
    
        // *** Do the initial check
        if (!checkCSS()) {
            // *** Didn't do it, add the listener
            window.addEventListener("load", checkCSS); // <== Note using the function directly
        }
    })();