首页 > 解决方案 > 让@HostListener 在开始之前等待

问题描述

我正在将@HostListener 滚动事件用于角度,我希望能找到一种方法让它在它执行任何操作之前等待 3 秒,但仅在第一次触发时

@HostListener('window:scroll', ['$event']) getScrollHeight(event) {

  const numberWhenItEntersViewport =
    document.getElementById("innerScreenSection").offsetTop -
    document.documentElement.clientHeight;
  const yValueBottomOfElement =
    document.getElementById("innerScreenSection").offsetTop +
    document.getElementById("innerScreenSection").offsetHeight;
  const elementHeight = document.getElementById("innerScreenSection")
    .offsetHeight;

  // if the element is where I want it and the timer has not gone yet then start the timer
  // I realize I never declare waitedThreeSeconds, this is just for show of what I'm thinking
  if (
    waitedThreeSeconds === false &&
    window.pageYOffset >= numberWhenItEntersViewport + 0.25 * elementHeight &&
    window.pageYOffset <= yValueBottomOfElement - 0.3 * elementHeight
  ) {
    // start timer and set waitedThreeSeconds to true? Idk how to do this without declaring
    // a varible in here and having it turned back to false everytime this function is called
    // it also does not seem to be able to read variables outside of this function
    // specifically when they change it doesnt update
  } else {
    // 3 seconds have passed
    console.log("scrolling and 3 seconds have passed");
  }
}

标签: angular

解决方案


    import { Subject, Observable } from 'rxjs';
    import { delay, concatMap } from 'rxjs/operators';

    // Delay amount (ms)
    const DELAY = 3000;

...

    // Setup
    private readonly eventStream = new Subject<Event>();

    // On the first emission, delay.
    // After the delay, REMAP to the original stream (concatMap)
    // USE first() to complete outer observable.
    get eventStream$(): Observable<Event> {
      return this.eventStream.pipe(
        delay(DELAY),
        first(),
        concatMap(() => this.eventStream)
      );
    }

      // Listen to clicks and emit
      @HostListener('window:scroll', ['$event']) scroll(event: Event) {
        this.eventStream.next(event);
      }

      constructor() {
        this.eventStream$.subscribe(this.isScroll);
      }

      isScroll(event: Event) {
        // Do math here.
        console.log(event);
      }

      ngOnDestroy() {
        // Cleanup.
        this.eventStream.unsubscribe();
      }

现在我们可以继续限制响应等。


推荐阅读