这是我的代码:
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 计时器如何工作的有趣文章:
- How JavaScript Timers Work作者:约翰·雷西格
更新:
除了更新的问题之外,您可能还想监听 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/