最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop execution of the getCurrentPosition method - Stack Overflow

programmeradmin2浏览0评论

I'm using the getCurrentPosition method in Javascript. I would like to implement a button that stops the execution of the method "getCurrentPosition" when it's clicked. I tried with throw/try/catch blocks but it doesn't seem to work :


    try {
        $('#cancel').on("click", function() { 
            $.mobile.loading('hide'); 
            throw "stop";
        });
        navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy: true, timeout : 30000 }); 
    }
    catch ( er ) { alert(er); return false; }

Any ideas? Is it even possible in JS ? I had an idea but I don't know if it's possible to trigger a timeout with a JS method so that the getCurrentPosition breaks ?

I'm using the getCurrentPosition method in Javascript. I would like to implement a button that stops the execution of the method "getCurrentPosition" when it's clicked. I tried with throw/try/catch blocks but it doesn't seem to work :


    try {
        $('#cancel').on("click", function() { 
            $.mobile.loading('hide'); 
            throw "stop";
        });
        navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy: true, timeout : 30000 }); 
    }
    catch ( er ) { alert(er); return false; }

Any ideas? Is it even possible in JS ? I had an idea but I don't know if it's possible to trigger a timeout with a JS method so that the getCurrentPosition breaks ?

Share Improve this question edited Apr 16, 2013 at 20:02 Gajotres 57.3k16 gold badges105 silver badges131 bronze badges asked Apr 11, 2013 at 14:50 LailaLaila 1,5113 gold badges14 silver badges28 bronze badges 2
  • It's supposed to be an asynchronous method so shouldn't stop rendering or anything but the w3 spec doesn't allow you to stop it once started. Do you just want to ignore the result if the button is clicked? The code you posted has no chance of working, events and asynch methods do not work that way. – mattmanser Commented Apr 11, 2013 at 15:16
  • When the button is clicked, I want to stop the execution of getCurrentPosition (with something similar to clearTimeout). – Laila Commented Apr 11, 2013 at 15:20
Add a ment  | 

1 Answer 1

Reset to default 17

Solution:

Method navigator.geolocation.getCurrentPosition is an asynchronous function so don't count on stopping it just like that.

You should instead use other function called: navigator.geolocation.watchPosition. It works in the same way as getCurrentPosition but what make it usefull in your case is another function called navigator.geolocation.clearWatch and that function is used to stop watchPosition.

Example:

geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
geoLoc.clearWatch(watchID);
发布评论

评论列表(0)

  1. 暂无评论