setTimeout循环检查边界变化 [英] setTimeout in loop to check for a change in bounds
问题描述
这是我的代码:
var b;
while(!b){
setTimeout(function(){
alert('sss')
b=1;
}, 500);
}
它不会提醒'sss'
我该怎么办?
已更新:
我想了解Google Maps v3的范围:
I want to get bounds on google maps 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,我不知道为什么,但是您的代码不起作用:
hi patrick dw, i don't know why , but your code doesn't work:
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()
推荐答案
Web浏览器中的JavaScript在单个线程中运行.调用setTimeout()
时,它不会产生新线程.这意味着setTimeout()
在所有主要代码完成执行之前不会执行.
JavaScript in web browsers is run in a single thread. When you call setTimeout()
, it won't spawn a new thread. This means that setTimeout()
will not execute until all of your main code has finished executing.
由于这个原因,您将最终陷入无限循环,因为您的循环条件取决于setTimeout()
回调的执行.
For this reason, you will end up with an infinite loop, because your loop condition is dependant on the execution of the setTimeout()
callback.
这是一篇有关JavaScript计时器如何工作的有趣文章:
Here's an interesting article on how JavaScript timers work:
- JavaScript计时器的工作原理,约翰·雷西格(John Resig)
- How JavaScript Timers Work by John Resig
更新:
在更新后的问题中,您可能想收听bounds_changed
事件.我不确定您打算如何使用get_bounds()
函数,但是您可能希望重构逻辑以改为使用事件侦听器:
Further to the updated question, you may want to listen to the bounds_changed
event instead. I am not sure how you are planning to use your get_bounds()
function, but you may want to refactor your logic to use an event listener instead:
google.maps.event.addListener(map,'bounds_changed', function () {
// The code here is triggered when the bounds change
});
这篇关于setTimeout循环检查边界变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!