【发布时间】:2011-11-03 19:52:02
【问题描述】:
我在 JavaScript 中使用 navigator.geolocation.watchPosition,我想要一种方法来处理用户可能在 watchPosition 找到其位置之前提交依赖位置的表单的可能性。
理想情况下,用户会定期看到“等待位置”消息,直到获得位置,然后提交表单。
但是,由于缺少 wait 函数,我不确定如何在 JavaScript 中实现它。
当前代码:
var current_latlng = null;
function gpsSuccess(pos){
//console.log('gpsSuccess');
if (pos.coords) {
lat = pos.coords.latitude;
lng = pos.coords.longitude;
}
else {
lat = pos.latitude;
lng = pos.longitude;
}
current_latlng = new google.maps.LatLng(lat, lng);
}
watchId = navigator.geolocation.watchPosition(gpsSuccess,
gpsFail, {timeout:5000, maximumAge: 300000});
$('#route-form').submit(function(event) {
// User submits form, we need their location...
while(current_location==null) {
toastMessage('Waiting for your location...');
wait(500); // What should I use instead?
}
// Continue with location found...
});
【问题讨论】:
-
异步思考。查找
setTimeout。 -
异步和递归可能 - 递归调用 setTimeout 直到 current_latlng 有一些价值?
-
在指责它之前先了解语言。肯定不会“缺少”
wait函数。 -
@Richard 是的,但无论你做什么都使用超时。当以任何方式(几乎所有)连续运行时,Javascript 将使用多少 CPU 资源,您会感到惊讶。
-
@Richard:没错。由于异步性,它不是严格的函数调用递归,但从代码的角度来看,确实如此。