禁止循环函数

Prohibit looping functions

本文关键字:函数 循环 禁止      更新时间:2023-09-26

函数onSuccess无限期运行,因为它不断地向GPS接收器询问坐标。它包含一个只执行一次的createMap函数。这是如何实现的呢?在函数之外做一个函数也不能,因为它是作为参数值传递给函数的一个变量。

watchID = navigator.geolocation.watchPosition(function(position) {onSuccess(position, arrMyLatLng);}, onError, options);  
function onSuccess(position, arrMyLatLng) 
{
var latitude , longitude ;     
latitude = position.coords.latitude ;
longitude = position.coords.longitude;
var myLatLng = new google.maps.LatLng(latitude, longitude);
createMap(myLatLng, arrMyLatLng);// This feature will run for an indefinite number of times. It is only necessary once. 
map.panTo(myLatLng) ;
}

可以使用闭包创建私有状态的函数:

onSuccess = (function() {
    var created = false;
    return function (position, arrMyLatLng) {
        var latitude , longitude ;     
        latitude = position.coords.latitude ;
        longitude = position.coords.longitude;
        var myLatLng = new google.maps.LatLng(latitude, longitude);
        if (!created) {
            createMap(myLatLng, arrMyLatLng);
            created = true;
        }
        map.panTo(myLatLng) ;
    };
}());

只运行一次的函数:

function runOnce() {
    if (runOnce.done) {
         return;
    } else {
       // do my code ...
       runOnce.done = true;
    }
}

因为函数在JavaScript中是对象,所以你可以给它设置一个属性

假设createMap返回映射

var map = null;
function onSuccess(position, arrMyLatLng) {
    var latitude = position.coords.latitude ;
    var longitude = position.coords.longitude;
    var myLatLng = new google.maps.LatLng(latitude, longitude);
    map = map || createMap(myLatLng, arrMyLatLng);
    map.panTo(myLatLng);
}

createMap只在map计算为"false"(即null)时运行,因此createMap只运行一次。