2

I have some code for swipe gesture, the main parts are:

this.topSlide = this.elementRef.nativeElement.querySelector('.product_rate_slide');
if (this.topSlide) {
    this.topSlide.addEventListener('touchstart', this.handleTouchStart);
    this.topSlide.addEventListener('touchmove', this.handleTouchMove);
    this.topSlide.addEventListener('touchend', this.handleTouchEnd);
}

and this is a part of the handler for TouchEnd:

private handleTouchEnd = (evt) => {
    if (this.left > 150) {
        const rightInterval = setInterval(() => {
            this.left += 30;
            if (this.left > 500) {
                clearInterval(rightInterval);
                this.removeTopSlide();
                this.addListener();
                this.slideSwiped.emit(evt);
            }
            this.cdr.detectChanges();
        }, 17);

Code inside setInterval gets called every 2 seconds (note the interval is set to 17ms)

This works fine on fast machines, the problem occurs when running on a real mobile device (tested with Samsung Galaxy S8) or setting Chrome Performance CPU throttling to 6x slowdown.

Chrome Performance

Tzach Ovadia
  • 1,278
  • 9
  • 18

1 Answers1

3

The timeout is more a 'request', if the device is too busy doing other stuff, like repainting the DOM and it is not fast enough to keep up, you get delays longer than you want.

So it can be that you need to do something different on slow devices. Besides that: it is better to use setTimeout than setInterval, set a new timeout when the first call is finished. So events don't stack up and get fired at the same time.

Reference (check: Reasons for delays longer than specified): https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified

Jørgen
  • 2,157
  • 1
  • 23
  • 24