You need to enable JavaScript to run this app. 如何为onToggle内的scroller.scrollTo设置执行前0.5秒延迟
优惠活动
大模型
产品
解决方案
定价
更多

如何为onToggle内的scroller.scrollTo设置执行前0.5秒延迟

滚动前置0.5秒延迟的实现方法

原有激活状态更新逻辑无需调整,仅需将scroller.scrollTo的调用包裹在指定时长的延迟定时器中即可,注意做好定时器清理避免运行异常。

  • 基础版本实现
    直接给滚动调用增加500ms(即要求的0.5秒)前置延迟,核心代码改动如下:
const onToggle = (id) => {
  setActive(id === active ? null : id);

  // 预留0.5秒缓冲后再执行滚动定位
  setTimeout(() => {
    scroller.scrollTo(id, {
      smooth: true,
      duration: 500,
      spy: true,
      exact: true,
      offset: -15,
    });
  }, 500);
};
  • 适配高频触发场景的优化实现
    如果存在快速连续点击触发onToggle的情况,需要补充定时器清理逻辑,避免多个延迟任务排队执行导致滚动错位。在React组件中可通过ref存储定时器引用,配合组件卸载钩子释放资源:
import { useRef, useEffect } from 'react';

// 用ref存储定时器ID,避免组件重渲染丢失引用
const scrollTimerRef = useRef(null);

const onToggle = (id) => {
  setActive(id === active ? null : id);

  // 触发新逻辑前清除上一次未执行的延迟任务
  if (scrollTimerRef.current) {
    clearTimeout(scrollTimerRef.current);
  }

  scrollTimerRef.current = setTimeout(() => {
    scroller.scrollTo(id, {
      smooth: true,
      duration: 500,
      spy: true,
      exact: true,
      offset: -15,
    });
  }, 500);
};

// 组件卸载时清理定时器,避免内存泄漏
useEffect(() => {
  return () => {
    if (scrollTimerRef.current) clearTimeout(scrollTimerRef.current);
  };
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 04:36:02