
export default function scroll(dom) {
  let scrolling = false;
  let t1 = undefined;
  const timeDiff = 500;

  const scrollStart = { value: undefined };
  const scrollEnd = { value: undefined };
  
  const onScroll = (e) => {
    if (!scrolling) {
      if (typeof scrollStart.value === 'function') {
        scrollStart.value(e);
      }
    }

    scrolling = true;

    if (t1) {
      // 如果存在计时器 t1, 说明在滚动
      // 立即销毁 t1
      clearTimeout(t1);
      t1 = undefined;
    }

    // t1 主要的作用是触发 stop 事件
    t1 = setTimeout(() => {
      // 如果 t1 被触发, 没有被销毁 说明没有在滚动
      clearTimeout(t1);
      t1 = undefined;
      scrolling = false;

      if (typeof scrollEnd.value === 'function') {
        scrollEnd.value(e);
      }
    }, timeDiff);
  }

  dom.addEventListener('scroll', onScroll);

  return {
    onStart: cb => scrollStart.value = cb,
    onEnd: cb => scrollEnd.value = cb,
    destroy: () => dom.removeEventListener('scroll', onScroll)
  }
}
