最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

Let me start here. At w3cshools - .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 remended 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?

Let me start here. At w3cshools. - http://www.w3schools./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 remended 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?

Share Improve this question asked Nov 9, 2011 at 8:13 John GathogoJohn Gathogo 4,6653 gold badges35 silver badges49 bronze badges 1
  • "surprisingly it has a mismatched </form>"... w3fools. (As for your actual problem, you should never pass a string to setInterval. Pass a reference to the function instead, which as you've said, works fine.) – James Allardice Commented Nov 9, 2011 at 8:15
Add a ment  | 

4 Answers 4

Reset to default 5

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.

The reason that the browsers say that the function isn't defined, is that it's not defined in the scope where the interval runs. You have declared the function locally inside another function, so it doesn't exist in the global scope where the interval runs.

This is not due to jQuery, simply due to the anonymous function that you wrap the code in. This code shows the same error:

(function() {

  function testMessage() {
    window.alert("Hello");
  }

  var refreshIntervalId = window.setInterval("testMessage()", 5000);

})();

You can declare the function globally instead, then you can use a string for the interval:

function testMessage() {
  window.alert("Hello");
}

(function() {

  var refreshIntervalId = window.setInterval("testMessage()", 5000);

})();

Common practice is to use the function itself rather than a string in the interval call:

(function() {

  function testMessage() {
    window.alert("Hello");
  }

  var refreshIntervalId = window.setInterval(testMessage, 5000);

})();

If you need to pass a value to the function, you can use an anonymous function in the call:

(function() {

  function testMessage(msg) {
    window.alert(msg);
  }

  var refreshIntervalId = window.setInterval(function() { testMessage("Hello"); }, 5000);

})();

function testMessage() and any other function must be declared OUTSIDE $(document).ready()

as @Quentin mentioned it's because the testMessage function is defined within the document ready and so outside the scope of the interval.

If you must define you're interval within the document ready you could do

refreshIntervalId = setInterval(function() {
    window.alert("Hello");
}, 5000);
发布评论

评论列表(0)

  1. 暂无评论