微信小程序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();
  }
})

最后注意清除定时器:

相关推荐
小徐_233315 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
山河木马16 小时前
矩阵专题3-怎么创建投影矩阵(uProjectionMatrix)
javascript·webgl·计算机图形学
泯泷18 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
泯泷18 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
朦胧之18 小时前
页面白屏卡住排查方法
前端·javascript
犇驫聊AI19 小时前
Chrome DevTools MCP + Claude Code 自定义skills生成接口代码生成器
前端·javascript
kyriewen19 小时前
别再这样写 async/await 了:我在 Code Review 中见过最多的 8 个错误
前端·javascript·面试
用户298698530141 天前
在 React 中使用 JavaScript 将 Excel 转换为 SVG
前端·javascript·react.js
labixiong1 天前
手写Promise--微任务、静态方法、async/await 全搞懂(三)
前端·javascript
铁皮饭盒1 天前
3行代码搞定页面截图,Bun.WebView真的简单
javascript