开发者

setTimeout() causing slowdown and not exiting properly

开发者 https://www.devze.com 2023-03-11 23:56 出处:网络
Clarification: The parent frame is Page X, the child frame resides within page X. The issue is the slow behavior and never hitting the section of code that clears the interval.

Clarification: The parent frame is Page X, the child frame resides within page X. The issue is the slow behavior and never hitting the section of code that clears the interval.

I have a parent and chilframe. An object is created in the parent then I used setTimeout() in the childframe to call the parent object to add itself to an internal collection within the parent object.

The code doesn't seem to behave as intended with really slow response from the browser. Any开发者_如何学JAVA thoughts on the issue?

Parent frame

<script type="text/javascript">
       var Cert = new Parent();
    </script>

Child frame

<script  type="text/javascript">
        var c;
        var id = setInterval("Create()", 1000);

        function Create()
        {
            if (parent.Cert != null && parent.Cert != undefined)
            {
                c = new Child(parent.Cert, 1, null);
                clearInterval(id);
            }
        }
    </script>


Don't pass a string to setTimeout/Interval. Pass it a function reference instead!

var id = setInterval(function () {
    Create();
}, 1000);

From the code you've given here, parent is window. Is this what you intend? There seems to be some relevant code missing here...

As for the slowdown, perhaps the function interval is too short, or it is never being satisfied? There could also be an error in the constructor for the Child class, which would make it so the clearInterval line won't ever be called. You could consider putting a limiter out there, or wrapping your instantiation in a try...catch block, or moving the clearInterval statement above the line where you're creating your object.

Or, do all of those things:

    var c = null;
    var id = setInterval(function () {
        Create();
    }, 1000);

    var itr = 0;
    function Create() {
        // if it has looped more than 20 times, forget it
        if (itr > 20) {
           /* show an error message? */
           clearInterval(id);
           return false;
        }

        if (parent.Cert != null && typeof parent.Cert != 'undefined') {
            // clear the interval first
            clearInterval(id);
            // safely create object
            try {
                c = new Child(parent.Cert, 1, null);
            } catch (e) {
               /* handle exception here */
            }
        } else {
            // incrementing the interval counter
            itr++;
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消