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

最后注意清除定时器:

相关推荐
码路飞22 分钟前
GPT-5.3 Instant 终于学会好好说话了,顺手对比了下同天发布的 Gemini 3.1 Flash-Lite
java·javascript
Lee川23 分钟前
从回调地狱到同步之美:JavaScript异步编程的演进之路
javascript·面试
进击的尘埃24 分钟前
WebSocket 长连接方案设计:从心跳保活到断线重连的生产级实践
javascript
摸鱼的春哥2 小时前
Agent教程15:认识LangChain(中),状态机思维
前端·javascript·后端
明月_清风2 小时前
告别遮挡:用 scroll-padding 实现优雅的锚点跳转
前端·javascript
明月_清风2 小时前
原生 JS 侧边栏缩放:从 DOM 监听到底层优化
前端·javascript
炫饭第一名16 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
进击的尘埃18 小时前
Vue3 响应式原理:从 Proxy 到依赖收集,手撸一个迷你 reactivity
javascript
willow18 小时前
JavaScript数据类型整理1
javascript
LeeYaMaster18 小时前
20个例子掌握RxJS——第十一章实现 WebSocket 消息节流
javascript·angular.js