我在网站上使用Google Maps API。我显示路线,路线的距离和持续时间。因此,我有以下代码:
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: false,
map: map,
panel: document.getElementById('right-panel')});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('Zeiskamer Straße 1, 76756 Bellheim', 'Voelklingen', directionsService, directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true,
drivingOptions: {
departureTime: new Date(Date.now() + 100),
trafficModel: 'optimistic'
},
},
function(response, status) {
if (status === 'OK') {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
total = "Die Entfernung beträgt: <b>" +myroute.legs[0].distance.text +"</b>";
document.getElementById('total').innerHTML = total + "<br>"+ "Die voraussichtliche Fahrzeit beträgt: <b>" + myroute.legs[0].duration_in_traffic.text + "</b>" + seconds;
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap">
</script>
我希望{10}每10分钟更新duration_in_traffic
。但我不知道如何每10分钟执行一个带参数的函数。
我怎么能这样做?
答案 0 :(得分:2)
使用setInterval以重复的间隔执行任务
setInterval( function() { showAlert('this'); }, 10*60*1000 );
function showAlert(text){
alert("called "+text)
}
&#13;
答案 1 :(得分:0)
你必须设置一个定时器,每十分钟调用一次该功能:
function initMap() {
...
// Call initially
displayRoute('Zeiskamer Straße 1, 76756 Bellheim', 'Voelklingen', directionsService, directionsDisplay);
// And then call it again every 10 minutes
setInterval(function() {
displayRoute('Zeiskamer Straße 1, 76756 Bellheim', 'Voelklingen', directionsService, directionsDisplay);
}, 10 * 60 * 1000);
// ^ 10 minutes in ms
}
为方便起见,您可以将displayRoute
包装在另一个函数中:
function initMap() {
...
var displayRouteHandler = function () {
displayRoute('Zeiskamer Straße 1, 76756 Bellheim', 'Voelklingen', directionsService, directionsDisplay);
};
// Call initially
displayRouteHandler();
// And then call it again every 10 minutes
setInterval(displayRouteHandler, 10 * 60 * 1000);
// ^ 10 minutes in ms
}
这样做更好,因为您没有重复的代码。
答案 2 :(得分:0)
像这样使用setTimeout():
function one() {
console.log(+new Date());
setTimeout(function() {
one();
}, 1000)
}
one();
&#13;
每一秒都会改变价值; 您可以使用setTimeout(回调,10 * 60 * 1000)每10分钟进行第二次回调
答案 3 :(得分:0)
使用setInterval在一定时间后反复执行某些操作。
setInterval(function(){
console.log("test");
},3000);
记录&#34;测试&#34;每3秒钟后。