0

I've written a function to catch a loop after it has run over a specified time.

var t1 = new Date().getTime();
while(true){
    //general code in here...

    document.body.appendChild(document.createElement('div')); //This causes the problem

    if(isInfinite(t1,3000)){
        alert('Loop stopped after 3 seconds')
        break;
    }       
}


function isInfinite(t1,timeLimit){
    var t2 = new Date().getTime();
    if(t2-t1> timeLimit){
        return true;
    }
    else return false;
}

It works as expected, but when I try to append nodes to the document it fails to catch in chrome & safari. What's weird is it works when I have the debugger running, and it works in FF. What is causing this?

4

1 回答 1

0

也许你在 DOM 准备好之前触发了这个 JS 代码。这是我的实现。

<!--Basically I am firing this script with onload event function.-->
<html>
    <head></head>
    <body onload="init()">
        <script>
            function init() {
                alert("asg");
                var t1 = new Date().getTime();
                while(true) {
                    //general code in here...
                    document.body.appendChild(document.createElement('div')); //This causes the problem
                    if(isInfinite(t1, 3000)) {
                        alert('Loop stopped after 3 seconds')
                        break;
                    }
                }

                function isInfinite(t1, timeLimit) {
                    var t2 = new Date().getTime();
                    if(t2 - t1 > timeLimit) {
                        return truite;
                    } else return false;
                }
            }
        </script>
    </body>
</html>

然而,这个脚本很可能会崩溃,这取决于浏览器制造商如何设置循环限制(这通常发生在主线程被阻塞时)。所以我认为在这个例子中使用 setTimeout 函数会更好。


只为你的兴趣

Javascript 是基于事件的,它只有 1 个线程。您已经提到您将向初学者展示它。为什么不向他们解释 JS 的基于事件的性质,而不是这样做呢?

于 2013-03-24T07:02:17.410 回答