JavaScript: supposed to execute functions sequentially, not actually doing so?
I'm seeing a lot of answers on StackOverflow that say that JavaScript executes code sequentially, but I can actually see my own JavaScript not doing so. From the following code:
function centre_map(lat, lng, zoom_level) {
alert('centre_map');
map = new GMap2(document.getElementById('map_canvas'));
var latlng = new GLatLng(lat, lng);
map.setCenter(latlng, zoom_level);
}
function add_markers_within_bounds() {
alert('add_markers_within_bounds');
// add numerous BLUE markers within map bounds using MarkerClusterer
}
function add_marker(lat, lng, place_name, grid, county) {
alert('add_marker');
// add one ordinary RE开发者_运维问答D Google Maps marker
}
centre_map('{{lat}}', '{{lng}}', 12);
add_markers_within_bounds('{{grid}}', '{{place_name}}');
add_marker('{{lat}}', '{{lng}}', '{{place_name}}', '{{grid}}', '{{county}}');
I get the following sequence of events:
- 'centre_map' alert
- 'add_markers_within_bounds' alert
- 'add_marker' alert
- individual RED marker appears on map (i.e. add_marker renders)
- multiple BLUE markers appear on map (i.e. add_markers_within_bounds renders)
Why doesn't add_markers_within_bounds
complete before add_marker
gets under way: and how can I make it do so?
I know that one way might be to call add_marker
from within add_markers_within_bounds
, but for various reasons I'd rather keep it as a separate function.
The Google Maps API sometimes involves sending a request to Google to get the data. If one of these actions involves requesting data, it will be delayed until the HTTP request is complete, and the rest of the code will continue on without it.
It seems to me that add_marker
probably does not involve requesting data, since you already provide the coordinates, whereas add_markers_within_bounds
may involve downloading data to know what the coordinates actually are. As such, add_marker
will always happen first, while the data for the other markers is still busy downloading.
I'm not sure how the Google Maps API works, but you may be able to specify add_marker
as a callback to occur once all the data for add_markers_within_bounds
is ready.
Perhaps the operations on GMap2
are asynchronous (likely with A JAX)? If so, you may need to put a block operation after the call if you want to be sure of sequence.
as I understand you want that function to be called after the execution of the former. this might help you but i m not 100% sure as i couldnt test it for a scenario similar to yours.
window.setTimeout(function () {
add_marker();
}, 0);
giving 0 as set timeout's time forces it to execute it at the end
精彩评论