循环中的setTimeout以检查边界的变化

zjm*_*126 2 javascript google-maps while-loop settimeout

这是我的代码:

var b;
while(!b){
    setTimeout(function(){
        alert('sss')
        b=1;
    }, 500);
}
Run Code Online (Sandbox Code Playgroud)

它不会提醒'sss'

我能做什么?

更新:

我想在谷歌地图v3上受到限制:

function get_bounds(){
            var bounds_;
            while(!bounds_){
                setTimeout(function(){
                    bounds_=map.getBounds();
                    if(bounds_){
                        var leftBottom=[bounds_.getSouthWest().lat(),bounds_.getSouthWest().lng()]
                        var rightTop=[bounds_.getNorthEast().lat(),bounds_.getNorthEast().lng()]
                        return [leftBottom,rightTop];
                        }
                }, 500);
            }
        }
Run Code Online (Sandbox Code Playgroud)

updated2:

嗨patrick dw,我不知道为什么,但你的代码不起作用:

var b;
function waitForB() {
    setTimeout(function(){
        if(!b)
            waitForB();
        else
            alert('sss');
    }, 500);
}
waitForB()
Run Code Online (Sandbox Code Playgroud)

updated3:

现在好了:

var b;
function waitForB() {
    setTimeout(function(){
        if(!b){
            waitForB();
            b='ss';
        }
        else{
            alert('sss')
        }
    }, 500);
}
waitForB()
Run Code Online (Sandbox Code Playgroud)

Dan*_*llo 5

Web浏览器中的JavaScript在单个线程中运行.当你打电话时setTimeout(),它不会产生新的线程.这意味着setTimeout()在所有主代码完成执行之前不会执行.

因此,最终会出现无限循环,因为循环条件取决于setTimeout()回调的执行.

这是一篇关于JavaScript定时器如何工作的有趣文章:


更新:

除了更新的问题,您可能希望收听该bounds_changed事件.我不确定您打算如何使用您的get_bounds()函数,但您可能希望重构逻辑以使用事件侦听器:

google.maps.event.addListener(map,'bounds_changed', function () {
   // The code here is triggered when the bounds change
});
Run Code Online (Sandbox Code Playgroud)