繁体   English   中英

JS:Function 运行速度太快但不想使用 setTimeout 的快速补丁

[英]JS: Function running too fast but don't want to use quick patch of a setTimeout

然后在gestureEnd ,我调用checkInView() ,它遍历img标签并检查查看哪个在视图中。 如果它在视图中,我会缩小它(稍后会添加过渡)。
问题是checkInView()运行太快。 我通过在checkInView()运行之前添加setTimeout几秒钟来测试它,但我删除了它,因为它感觉很hacky。 还有其他方法可以解决这个问题吗?

     function isElementInViewport(el) {
        var rect = el.getBoundingClientRect();
        return rect.bottom > 0 &&
            rect.right > 0 &&
            rect.left < (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ &&
            rect.top < (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */;
    }

    function checkInView() {
        let images = document.querySelectorAll('img');
        for (let x of images) {
            if (isElementInViewport(x)) {
                x.style.height = "99px"
            }
        }
    }

    function goBack() {
        let carouselImagesContainer = document.querySelector('.carousel-container');
        carouselImagesContainer.scrollLeft -= carousels[0].clientWidth
    }

    function goForward() {
        let carouselImagesContainer = document.querySelector('.carousel-container');
        carouselImagesContainer.scrollLeft += carousels[0].clientWidth
    }
    function gestureEnd(evt2) {
        let endPoint = evt2.changedTouches[0].screenX;
        let total = endPoint - startingPoint;
        if (Math.abs(total) < 50) {
            return;
        }
        if (total > 0) {
            let foo = window.requestAnimationFrame(goBack)
        } else {
            let foo = window.requestAnimationFrame(goForward)
        }
        checkInView()
    }

我找到了一个解决方案,虽然我不知道这是否是一种可接受的方式:为了确保在运行 checkInView() 之前完成 goBack 和/或 goForward,我使用了 Promise.resolve()

function goBack() {
    Promise.resolve().then(() => {
        let carouselImagesContainer = document.querySelector('.carousel-container');
        carouselImagesContainer.scrollLeft -= carousels[0].clientWidth
    })
    .then(() => {
        checkInView()
    })
}

function goForward() {
    Promise.resolve().then(() => {
        let carouselImagesContainer = document.querySelector('.carousel-container');
        carouselImagesContainer.scrollLeft += carousels[0].clientWidth
    })
    .then(() => {
        checkInView()
    })
}

对于 Promises,这是可以接受的还是好的用例?

我建议您使用图像数组和 current_id 变量,因为您要来回查看视图中的图像很简单。 这是您可以执行的操作的示例:

var images = []; // fill this when app is ready?
var current_id = 0; // images[0] is the first image in the carousel

goBack() {
 // other stuff here...
 current_id--;
 images[current_id].style.height = "99px";
}

goForward(){
// other stuff here
current_id++;
images[current_id].style.height = "99px";
}

暂无
暂无

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

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