I am currently trying to set up a timeout timer for a device. My initial thought is to create a time out for 15 minutes then have an interval, every minute, request the location of the device and compare it to the device's previous location. If location is greater than some threshold then reset the 15 minute timer. If the location is not greater than the threshold then the timeout continues until the 15 minutes runs out and I run some other code.
My problem is that I cant wait to get the new location in side of the interval
timeoutFunc(minutes) {
return setTimeout(function () {
console.log("lock device")
}, minutes * 1000)
}
async rideTimer(minutes) {
let coords = this.location
this.timeOut = timeoutFunc(minutes) // init timeout func
let interval = setInterval(function () {
console.log(coords)
let newLocation = await getLocation() // get location
console.log(this.location)
// check if location changed
if (Math.abs(this.location[0] - coords[0]) > 0.001 || Math.abs(this.location[1] - coords[1]) > 0.001) {
// location did change
clearTimeout(this.timer) // clear timeout
this.timeOut = timeoutFunc(minutes) // reinitialize timeout
}// else do nothing
}, 1000)
}
await can only be used with async functions.
And you can use async functions with timers:
function dummyGetData() {
return new Promise(resolve => setTimeout(()=>resolve(new Date), 20));
}
const timer_end = Date.now() + 5000;
let timer = setInterval( async ()=> {
const data = await dummyGetData();
console.log(data);
if (timer_end < Date.now()) clearInterval(timer);
},1000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With