javascript - setTimeout 在循环中检查边界变化

标签 javascript google-maps while-loop settimeout

这是我的代码:

var b;
while(!b){
    setTimeout(function(){
        alert('sss')
        b=1;
    }, 500);
}

并且它不会提醒“sss”

我能做什么?

更新:

我想获取 google map 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);
            }
        }

更新2:

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

var b;
function waitForB() {
    setTimeout(function(){
        if(!b)
            waitForB();
        else
            alert('sss');
    }, 500);
}
waitForB()

更新3:

现在可以了:

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

最佳答案

网络浏览器中的 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
});

关于javascript - setTimeout 在循环中检查边界变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19983043/

相关文章:

java - Android google maps v2 无法在移动互联网(3g 或 4g)上运行,但可以在 wifi 上运行

php - 当检测到错误时重新启动 while 循环的当前操作

javascript - 如何编写 While 循环来提示一个单词并退出另一个单词的循环

java - While循环不起作用错误: bad operand types for binary operator '!=' Java

javascript - 如何在 React (JSX) 中清除/重置状态内的数组

javascript - 结合设计师和网络开发工作的最佳策略是什么?

javascript - 单击选项卡时如何阻止页面重新加载? (jQuery)

javascript - 未加载选项卡 - Bootstrap 选项卡

javascript - 多边形对象引用问题的谷歌地图信息窗口

android - Geocoder getFromLocationName() 仅返回 1 个结果