TransWikia.com

How would one call getCurrentPosition() every second?

Stack Overflow Asked by user11965730 on December 22, 2021

I am new to async functions. What I currently have is watchPosition(), which fires whenever a new position is detected. Well, what I need is to find a new speed every second. So, I want to call getCurrentPosition() every second, to record the speed of the user. I get a big backlog when I use setInterval() with getCurrentPosition().

What I want (time, speed):

1s, 1m/s
2s, 1.5m/s
3s, 1.2m/s...etc

What I get with setInterval and getCurrentPosition():

5s, 1m/s
5s, 1m/s
5s, 1m/s
10s, 1.5m/s
10s, 1.5m/s
10s, 1.5m/s...etc

With setInterval(), the speeds are all the same and I get a barrage of them every 5seconds or so. So I am confused, how should I approach this? Use an observable?


–edit:
With watchPosition():

function getAverageWalkingSpeed():any {
    var options = {
        maximumAge: 1000,
        timeout: 5000,
        enableHighAccuracy : true,
    };
    let watch = navigator.geolocation.watchPosition(onSuccess, onError, options);
    
    function onSuccess(position: { timestamp: string | number | Date; coords: { speed: any; latitude: any; longitude: any; }; }) {
        let time = formatTime(new Date(new Date().getTime())); //time when speed was found
        let speed = position.coords.speed;
        console.log(time,speed)
    })
}

With a setInterval function, replacing previous watchPosition() with getCurrentPosition(). Should just need to call setTimer(true):

function setTimer(state: boolean){
    if(state){
        var timer = setInterval(getAverageWalkingSpeed, 1000);
    }
    else{
        clearInterval(timer)
    }
}

One Answer

You can create a wrapper function that awaits for getCurrentPosition, and then recursively calls itself after 1 second:

function mockGetCurrentPosition () {
  return new Promise((resolve,reject)=> {
    setTimeout(()=> resolve(console.log("x,y")),1000); 
  });
}


async function getPosition () {
  await mockGetCurrentPosition(); 
  setTimeout(()=> getPosition(), 1000); 
}

getPosition(); 

Answered by Pavlos Karalis on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP