0

特定のターゲット精度が得られるまでデバイスの位置を取得する phonegap アプリ用に開発している JavaScript スクリプトがあります。目標が達成されない場合、スクリプトは自分自身を永遠に呼び戻します。通常、場所と最後に使用した時間に応じて 1 ~ 8 回の試行が必要で、その後はすべて正常に機能します。私が抱えている問題は、一部のデバイスがそのしきい値に到達しないことです (アプリにとっては問題ありません) が、このスクリプトがバックグラウンドで実行され続けるため、バッテリー寿命が台無しになります。では、クリック イベント (送信ボタン) でこのスクリプトを強制終了するにはどうすればよいでしょうか。送信ボタンを押すと変化するグローバル変数を設定することを考えていました。何かのようなもの:

if (var != 'quit') {
    //function 
} else {
    ///nothing
}

function getlocation(position) {
    document.getElementById("lat").value = (position.coords.latitude);
    document.getElementById("long").value = (position.coords.longitude);
    document.getElementById("accu").value = (position.coords.accuracy);
    var accuracy = parseInt(position.coords.accuracy, 10);
    if (accuracy <= 50) {
        $('#scanner').removeClass('littlered').addClass('littlegreen');
    } else {
        setTimeout(navigator.geolocation.getCurrentPosition(getDroplocation, onError, {
            enableHighAccuracy: true
        }), 3000);
    }
}

しかし、これは機能していません。グローバル変数を設定しましたが、何も起こりません。前述のアイデアを実現するためのより良い方法や方法はありますか? 私は正しい軌道に乗っていますか?

4

2 に答える 2

0

あなたはclearTimeoutが欲しい

変化する

function getlocation(position) {

var tId;
function getlocation(position) {

そしてsetTimeout_tId=setTimeout

そして、clearTimeout(tId);クリックしたいものをオンクリックするか、カウンターを追加して、10回ほど試行した後に殺します

例えば

<input type="button" id="togglebutton" value="Stop" />

使用して

var tId,startPosition="whateverdefaultpositionissetto";
window.onload=function() {
  document.getElementById("togglebutton").onclick = function() {
    if (tId) {
      clearTimeout(tId);
      this.value="Start";
    }
    else {
      getlocation(startPosition); 
      this.value="Stop";
    }
  }
}
于 2013-02-13T05:13:40.417 に答える
0

clearTimeout()メソッドを使用すると、setTimeout() メソッドで設定されたタイマーがクリアされます。

var to;

function getlocation(position) {
    document.getElementById("lat").value = (position.coords.latitude);
    document.getElementById("long").value = (position.coords.longitude);
    document.getElementById("accu").value = (position.coords.accuracy);
    var accuracy = parseInt(position.coords.accuracy, 10);
    if (accuracy <= 50) {
        $('#scanner').removeClass('littlered').addClass('littlegreen');
    } else {
        to = setTimeout(navigator.geolocation.getCurrentPosition(getDroplocation, onError, {
            enableHighAccuracy: true
        }), 3000);
    }
}

//Add click event handler to a button to stop the looping
var button = document.getElementById("testbtn");
testbtn.onclick = function() {
    clearTimeout(to);
}
于 2013-02-13T05:18:48.150 に答える