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

最后注意清除定时器:

相关推荐
徐同保8 分钟前
开发onlyoffice插件,功能是选择文本后立即通知父页面
开发语言·前端·javascript
23124_8014 分钟前
Base64多层嵌套解码
前端·javascript·数据库
菜鸟很沉29 分钟前
Vue3 + Element Plus 实现大文件分片上传组件(支持秒传、断点续传)
javascript·vue.js
Amumu1213830 分钟前
Vue核心(一)
前端·javascript·vue.js
敲敲了个代码31 分钟前
React 官方纪录片观后:核心原理解析与来龙去脉
前端·javascript·react.js·面试·架构·前端框架
研☆香39 分钟前
JavaScript 历史列表查询的方法
开发语言·javascript·ecmascript
钟佩颖44 分钟前
Vue....
前端·javascript·vue.js
漂流瓶jz1 小时前
Polyfill方式解决前端兼容性问题:core-js包结构与各种配置策略
前端·javascript·webpack·ecmascript·babel·polyfill·core-js
AC赳赳老秦1 小时前
低代码开发中的高效调试:基于 DeepSeek 的报错日志解析与自动修复方案生成
前端·javascript·低代码·postgresql·数据库架构·easyui·deepseek
大猫会长1 小时前
css中,由基准色提取其他变体
前端·javascript·html