我有一些JavaScript代码,如下所示:
function statechangedPostQuestion()
{
//alert("statechangedPostQuestion");
if (xmlhttp.readyState==4)
{
var topicId = xmlhttp.responseText;
setTimeout("postinsql(topicId)",4000);
}
}
function postinsql(topicId)
{
//alert(topicId);
}
Run Code Online (Sandbox Code Playgroud)
我得到一个topicId未定义的错误在使用该setTimeout()函数之前,一切正常.
我希望postinsql(topicId)在一段时间后调用我的函数.我该怎么办?
我navigator.geolocation.watchPosition在JavaScript中使用,我想要一种方法来处理用户在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...
});
Run Code Online (Sandbox Code Playgroud) 我知道它在这里被多次询问,很多次回答这不是应该怎么做的方式,而是再一次:)
是否有可能以某种方式调用异步函数(例如timer/ajax调用),基本上是常见的异步任务并同步等到它结束而没有100%的CPU使用率并阻止浏览器?
简单的回答就足够了 - 是或否.如果没有我必须根据"异步方式"中的异步操作编写所有代码,否则,它会更好;)
想象一下:
updateCSS("someurl.css")
function updateCSS(url) {
var css = getCachedResource(url);
css = css.replace(/regexp/gm, function(curUrl) {
base64 = atob(getCachedResource(curUrl))
return "data:image;base64," + base64
})
}
function getCachedResource(url) {
//...
if (cached) {
return cached
} else {
// doajax...
// watfor
return loaded
}
}Run Code Online (Sandbox Code Playgroud)
当然,我可以使它异步,但代码将......非常糟糕.而且,我必须使调用此函数的所有函数都异步.你能看到简单的解决方案吗 我会说阻塞是最简单的.
谢谢
javascript ×3
async-await ×1
asynchronous ×1
callback ×1
geolocation ×1
parameters ×1
promise ×1
settimeout ×1