微信小程序app.js中每30秒调用一次wx.getLocation

代码:

复制代码
const auth = require('./utils/auth.js');  // 引入 auth.js
// app.js
App({
  onLaunch() {
    // 原有登录检查逻辑
    const isLoggedIn = auth.checkLogin();
    if (!isLoggedIn) {
      wx.removeStorageSync('token');
      wx.removeStorageSync('userInfo');
      wx.reLaunch({ url: '/pages/login/login' });    
    }

    // 新增定时定位逻辑
    this.startLocationInterval();
  },

  startLocationInterval() {
    // 立即执行一次
    this.getAndCacheLocation();
    
    // 设置30秒定时器
    this.locationTimer = setInterval(() => {
      this.getAndCacheLocation();
    }, 30000);
  },

  getAndCacheLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        console.log("lat="+res.latitude+'&lon='+res.longitude)
        wx.setStorageSync('lastLocation', {
          latitude: res.latitude,
          longitude: res.longitude,
          timestamp: new Date().getTime()
        });
      },
      fail: (err) => {
        console.error('定位失败', err);
      }
    });
  },

  onHide() {
    // 小程序进入后台时清除定时器
    if (this.locationTimer) {
      clearInterval(this.locationTimer);
    }
  },

  onUnload() {
    // 双重保险
    if (this.locationTimer) {
      clearInterval(this.locationTimer);
      this.locationTimer = null;
    }
  },

  onShow() {
    // 小程序回到前台时重启定时器
    this.startLocationInterval();
  }
})

最后注意清除定时器:

相关推荐
liangshanbo12153 分钟前
JavaScript 异步核心主线
javascript·事件循环·异步操作
传人once1 小时前
悬停旋转放大和位移效果如何写
javascript·css·动画
光影少年2 小时前
Taro 是如何解析入口配置 app.config.ts 和页面配置的?
微信小程序·小程序·typescript·reactjs·百度小程序·taro
默_笙3 小时前
🍔 中间件不只是打日志:四个钩子、一次短路,和自带的工具
前端·javascript
Dovis(誓平步青云)4 小时前
家里设备越来越多,如何用一张空间地图控制灯光和温度![
android·java·前端·javascript·人工智能·电脑
xieter4 小时前
【技术精选】TypeScript 高级类型体操:条件类型与模板字面量深度剖析 (2026-10-06)
javascript
用户788477316344 小时前
门店核销闭环:小程序扫码 + .NET 幂等接口 + WPF 看板,一天能跑通
微信小程序·c#
ss2734 小时前
AI全栈实战 | 3.3-02 Python 并发:有 GIL 为什么还用多线程,asyncio 和 JS 事件循环同源不同味
开发语言·javascript·python
CappuccinoRose5 小时前
输入事件进阶
前端·javascript·输入事件
DS小龙哥7 小时前
从呼吸心率到离床报警:60G雷达睡眠仪全栈开发实录(硬件+MQTT+小程序)DIY一台全功能睡眠监护仪
stm32·单片机·嵌入式硬件·物联网·小程序·智能家居