在下面的代码中,我必须引入 setTimeOut()
来在第一个函数完全完成之前停止第二个函数的运行(请参阅 filterMovies()
的底部>)。在此之前,我尝试使用仅最终迭代调用回调(在我的情况下,相同的代码减去 setTimeOut() 和持续时间),但它仍然会在第一个代码完全运行之前运行已执行。
我认为这是因为我正在处理数百个 $(".movie")
元素(尽管我真的不知道)。
setTimeOut()
工作正常,但看起来不太优雅,无论是在页面上的编码还是性能方面(文本在延迟后更新)。本着更好的编码实践的精神,是否有一种更有效的方式来表达“嘿,updateSearchInfo
,在最后一个元素向上或向下滑动之前,甚至不要考虑运行?
function filterMovies() {
$(".movie").each(function(i) {
var movie = $(this);
var genreMatch =
!chosenGenres.length
? true
: chosenGenres.every(elem => movie.find(".genre").text().indexOf(elem) !== -1);
var directorMatch =
!chosenDirectors.length
? true
: chosenDirectors.every(elem => movie.find(".director").text().indexOf(elem) !== -1);
var countryMatch =
!chosenCountries.length
? true
: chosenCountries.every(elem => movie.find(".countries").text().indexOf(elem) !== -1);
i === $(".movie").length -1
? genreMatch && directorMatch && countryMatch
? movie.slideDown(setTimeout(function() {updateSearchInfo()}, 1000))
: movie.slideUp(setTimeout(function() {updateSearchInfo()}, 1000))
: genreMatch && directorMatch && countryMatch
? movie.slideDown()
: movie.slideUp();
});
}
function updateSearchInfo() {
movieCount = $(".movie:visible").length;
$("#search-info").text("Showing " + movieCount + " movies.");
}
提前致谢!
最佳答案
jQuery 的 slide*
函数采用在完成时运行的回调参数:
complete
Type: Function()
A function to call once the animation is complete, called once per matched element.
...
movie.slideDown(updateSearchInfo);
...
关于javascript - JavaScript 中有比 setTimeout 更好的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38851412/