dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

JS Function closures for persistent memory #105

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

Javascript functions can return other functions, and the inner function has access to the scope of the outer function, making it useful to store variables persistently between function calls, for example:

var checkCookie = function() {
    var lastCookie = document.cookie; // 'static' memory between function calls
    return function() {
        var currentCookie = document.cookie;

        if (currentCookie != lastCookie) {
            // something useful like parse cookie, run a callback fn, etc.
            lastCookie = currentCookie; // store latest cookie
        }
    };
}();
window.setInterval(checkCookie, 100); // run every 100 ms
dvas0004 commented 5 years ago

https://stackoverflow.com/questions/14344319/can-i-be-notified-of-cookie-changes-in-client-side-javascript