简体   繁体   English

Javascript 设置超时与 promise

[英]Javascript setTimeout with promise

I need to have promise type of actions in my code but not sure how should i change my code:我需要在我的代码中包含 promise 类型的操作,但不知道应该如何更改我的代码:

code代码

  scrollTo (id) {
    // add class to my DIV and scroll to it
    setTimeout(() => {
      var titleELe = document.getElementById(id);
      titleELe.classList.add('active');
      this.scrollMeElement.scrollToPoint(0, titleELe.offsetTop, 1000);
    }, 100);
    // remove that class from DIV
    setTimeout(() => {
      var titleELe = document.getElementById(id);
      titleELe.classList.remove('active');
    }, 600);
  };

Issue问题

The issue is that if my destination div (scrolled to) is close by every thing looks fine but if my DIV is far from current position before my scrolling process is done the class will be removed from it so the design isn't look as nice as is supposed to.问题是,如果我的目标 div(滚动到)靠近每件事看起来都很好,但是如果在我的滚动过程完成之前我的 DIV 与当前 position 相距甚远,则 class 将从其中删除,因此设计看起来不太好正如应该的那样。

What I need is to move my removing code of class after scrolling is done.我需要的是在滚动完成后移动我的删除代码 class 。

Logic:逻辑:

  1. Add class and scroll to destination DIV添加 class 并滚动到目标 DIV
  2. When scrolling is done, remove the class from destination DIV滚动完成后,从目标 DIV 中删除 class

Any idea on that?对此有任何想法吗?

As far as I can see scrollToPoint is returning Promise<void> ( https://ionicframework.com/docs/api/content ).据我所见, scrollToPoint正在返回Promise<void>https://ionicframework.com/docs/api/content )。

How about following simple solution?:下面简单的解决方案怎么样?:

scrollTo(id) {
    var scrollDuration = 800;
    var titleELe = document.getElementById(id);

    titleELe.classList.add('active');

    this.scrollMeElement.scrollToPoint(0, titleELe.offsetTop, scrollDuration).then(() => {
      titleELe.classList.remove('active');
    });
};

If you need the function to be async, then you can add outer promise as well:如果您需要 function 是异步的,那么您也可以添加外部 promise :

scrollTo(id) {
    return new Promise((resolve, reject) => {
        var scrollDuration = 800;
        var titleELe = document.getElementById(id);

        titleELe.classList.add('active');

        this.scrollMeElement.scrollToPoint(0, titleELe.offsetTop, scrollDuration).then(() => {
            titleELe.classList.remove('active');
            resolve();
        }, () => {
            reject();
        });
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM