You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用wavesurfer.js获取currentTime引发过度重渲染问题

解决React中wavesurfer.js播放时长频繁更新导致的重渲染问题

可以通过时间戳节流的方式,限制状态更新频率为每秒一次,具体实现如下:

  1. 新增useRef记录上次更新状态的时间戳,避免每次触发audioprocess都更新React状态
  2. 在audioprocess回调中判断当前时间与上次更新时间的差值,仅当差值≥1000ms时才更新状态
  3. 组件卸载时移除事件监听,防止内存泄漏

修改后的代码:

export function Component(){
    const [currentTime, setCurrentTime] = useState(0)
    const wavesurferRef = useRef<any>(null)
    // 记录上次更新状态的时间戳
    const lastUpdateTimeRef = useRef<number>(Date.now())

    useEffect(()=>{
        if (!wavesurferRef.current) return;

        // 定义命名回调函数,方便后续移除监听
        const handleAudioProcess = () => {
            const now = Date.now();
            // 仅当距离上次更新超过1秒时,才更新状态
            if (now - lastUpdateTimeRef.current >= 1000) {
                setCurrentTime(wavesurferRef.current.getCurrentTime());
                lastUpdateTimeRef.current = now;
            }
        }

        wavesurferRef.current.on('audioprocess', handleAudioProcess);

        // 组件卸载时移除事件监听
        return () => {
            wavesurferRef.current?.off('audioprocess', handleAudioProcess);
        }
    },[])
    

    return(
        <div>
            <div ref={wavesurferRef}></div>
            {/* 展示格式化后的播放时长 */}
            <p>当前播放时长: {Math.floor(currentTime)} 秒</p>
        </div>
    )
}

补充说明

  • 这种手动节流方式比第三方节流库更轻量,适合简单的时间间隔控制场景
  • 如果需要更精确的时长展示(比如保留一位小数),可以在更新状态时对getCurrentTime()的结果做格式化,同时保持每秒更新一次的频率
  • 必须清理事件监听,否则组件卸载后wavesurfer的回调仍可能触发,引发内存泄漏

内容的提问来源于stack exchange,提问作者Toby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:22:14