mafortis
mafortis

Reputation: 7128

Javascript setTimeout with promise

I need to have promise type of actions in my code but not sure how should i change my code:

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.

What I need is to move my removing code of class after scrolling is done.

Logic:

  1. Add class and scroll to destination DIV
  2. When scrolling is done, remove the class from destination DIV

Any idea on that?

Upvotes: 0

Views: 109

Answers (1)

Karol T
Karol T

Reputation: 1136

As far as I can see scrollToPoint is returning 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:

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();
        });
    });
};

Upvotes: 1

Related Questions