Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval odd (buggy?) behavior within a $(document).ready(function() { ... }); block

Let me start here. At w3cshools.com - http://www.w3schools.com/jsref/met_win_setinterval.asp - they have a snippet demo-ing how to use javascript setInterval function (surprisingly it has a mismatched </form> but thats beside the point).

I needed to use setInterval() and at times I like referring to some "standard" body to take a glimpse of the recommended usage. In my development environment, something seems to be mangling setInterval() behavior/working when I use it within a jquery $(document).ready(function() { ... }); block.

Illustration 1 - WORKS: Typical/Traditional <script> block

<script type="text/javascript">
    var refreshIntervalId;

    function testMessage() {
        window.alert("Hello");
    }
    refreshIntervalId = setInterval("testMessage()", 5000);
</script>

Illustration 2 - DOES NOT WORK: jQuery block

<script type="text/javascript">
    $(document).ready(function() {
        var refreshIntervalId;

        function testMessage() {
            window.alert("Hello");
        }
        refreshIntervalId = setInterval("testMessage()", 5000);
    });
</script>

Illustration 3 - WORKS: jQuery block - using setInterval(testMessage, 5000) instead of setInterval("testMessage()", 5000)

<script type="text/javascript">
    $(document).ready(function() {
        var refreshIntervalId;

        function testMessage() {
            window.alert("Hello");
        }
        refreshIntervalId = setInterval(testMessage, 5000);
    });
</script>

It turns out that if I try to pass the function as a string from with the $(document).ready(function() {}); block, I get an error indicating that the function is not defined. Just so we dont get side-tracked IE, Chrome, and Firefox all report errors:

IE: Microsoft JScript runtime error: The value of the property 'testMessage' is null or undefined, not a Function object

Chrome: Uncaught ReferenceError: testMessage is not defined (anonymous function)

Firefox: testMessage is not defined.

What I would like to find out (if possible) is, could this be a result of standards non-conformance or what be going wrong when I try to use setInterval("testMessage()", 5000) from within the jQuery block? Could some mangling be happening or is this the right behavior?

like image 822
John Gathogo Avatar asked May 09 '26 16:05

John Gathogo


1 Answers

setTimeout and setInterval break scope, so it can't find testMessage when it goes looking for it (because that function is scoped inside the anonymous function you pass to ready). Browsers are behaving correctly.

This is one of the reasons you should never, ever use the string format … or try to learn from the dreadful W3Schools.

like image 184
Quentin Avatar answered May 11 '26 05:05

Quentin