/** * 统计信息轮询 Worker * 功能:定时获取 VSLAM 统计信息(关键帧数量、闭环数量、运行状态) */ // 轮询定时器 ID let pollingIntervalId = null /** * 监听主线程消息 */ self.onmessage = function(event) { const action = event.data.action if (action === 'startPolling') { // 启动轮询 const { url, interval = 1000 } = event.data // 默认 1 秒轮询一次 // 停止现有轮询(防止重复) if (pollingIntervalId) { clearInterval(pollingIntervalId) } // 立即执行一次 const fetchStatistics = () => { fetch(url) .then(response => { if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`) } return response.json() }) .then(data => { // 返回数据到主线程 // 数据格式: { keyframes: 数量, closures: 闭环数, running: true/false } console.log('[StatisticsWorker] 获取成功:', data) self.postMessage({ type: 'success', data: data }) }) .catch(error => { console.error('[StatisticsWorker] 获取失败:', error) // 将错误发送回主线程 self.postMessage({ type: 'error', error: error.message }) }) } // 立即执行一次 fetchStatistics() // 开始定时轮询 pollingIntervalId = setInterval(fetchStatistics, interval) console.log('[StatisticsWorker] 启动轮询:', url, '间隔:', interval + 'ms') } else if (action === 'stopPolling') { // 停止轮询 if (pollingIntervalId) { clearInterval(pollingIntervalId) pollingIntervalId = null } } } /** * 错误处理 */ self.onerror = function(error) { console.error('Worker error:', error) }