简体   繁体   中英

IE8 problem with javascript function that calls itself in setTimeout

i have a locate function defined in javascript

var locID;

function locateMe()
{
    if(locID > 0)
    {
        // i do a jquery post here
    }

    setTimeout(locateMe, 2000);
} 

// my document ready function is here, and inside it, at the end of it
// i do this
locID = 0;
locateMe();

when i test this code in firefox, the locateMe function is called every two seconds and works as expected. when i test the code in IE8 the function is never called (at least it appears to never be called from what i can see using IE's developer tools)

note: there is code defined in a click event handler for the 'zone_row' class that modifies locID. again, in firefox everything works as expected. the strange thing is, in IE when a zone_row is clicked the function WILL be called ONCE. i can see that both on the developer tools and through the result of the action of that jquery post.

i figured there is just some anomly with IE that i am not familiar with yet. what am i doing wrong?

EDIT: changed "locateMe();" to locateMe inside the setTimeout call.

UPDATE: adding more of my code (per request in comments) to show placement (albeit not much more code than my first post).

<script type="text/javascript">
    var z_items;
    var locID;

    function locateMe()
    {
            if(locID > 0)
            {
                    // my jquery post is here                   
            }   

            setTimeout(locateMe, 2000);
    }

    $(document).ready(function()
    {
            // ... some click events and get requests here ...

            locID = 0;
            locateMe();
    });
</script>

i also tried wrapping the call in a setTimeout (no effect) and changing the DOCTYPE (this actually caused IE to never call the function as opposed to now where it calls it ONCE and never again).

problem solved. i found an answer to another problem i was having from this post:

Prevent browser caching of jQuery AJAX call result

upon adding $.ajaxSetup({ cache: false }); to my document ready function, it solved THIS problem too. it looks like all this time it was a caching issue.

I've found that for IE (even IE9) that if you nest the self-called function in an anonymous function it works. But it does look like Toddeman's problem was related to the ajax part.

So the code would be:

function locateMe()
{
    /* ... */   

    //IE way (still works in Chrome and FF):
    setTimeout(function () { locateMe(); }, 2000);

    //original: setTimeout(locateMe, 2000);
}

使用

setTimeout( locateMe, 2000 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM