• 10ott
    Categories: Programming Commenti disabilitati

    Passing arguments to the function repeated in setInterval is not implemented in Internet explorer; even if there is a documented way to pass parameters to it, this way only works in IE for static parameters. What about, for example, if you need to set an interval for a function that, in a certain moment, clears itself?

    Fortunately, javascript can do closures (as Actionscript does); which means that, having two nested functions, you can still access outer variables from the inner function even if the outer one has already terminated execution. Using this trick, you can define setInterval parameters as outer scope vars; in other words:

    function outerScope() {
        var arg = "Hello world!";
        var innerFn = function() {
            alert(arg);
            clearInterval(interval);
        };
        var interval = setInterval(innerFn(), 1000);
    }
    outerScope();

    The code above will alert a message after one second, then clear the repeating event. This could also be done with setTimeout as obviously the same applies to setTimeout. It's elegant and cross-browser. Knowing language characteristics can help you write much less code...