[英]Is there something better than setTimeout in JavaScript?
In the code below I have had to introduce setTimeOut()
to stop the second function running before the first function has completely finished (see towards the bottom of filterMovies()
). 在下面的代码中,我必须引入
setTimeOut()
才能在第一个函数完全完成之前停止第二个函数的运行(请参阅filterMovies()
的底部)。 Before that, I was trying to use both a final-iteration-only call callback (in my case the same code minus the setTimeOut()
and duration) but it would still run before the first code had fully executed. 在此之前,我试图同时使用仅最终迭代的调用回调(在我的情况下,相同的代码减去
setTimeOut()
和持续时间),但它仍将在第一个代码完全执行之前运行。
I presume this is because I'm dealing with a couple of hundred $(".movie")
elements (although I don't really know). 我认为这是因为我正在处理数百个
$(".movie")
元素(尽管我不太清楚)。
setTimeOut()
works okay but it seems inelegant, both in terms of coding and performance on the page (the text updates after a delay). setTimeOut()
可以正常工作,但是就页面的编码和性能而言(在延迟后文本会更新)都显得不佳。 In the spirit of better coding practice, is there a more efficient way of saying "hey, updateSearchInfo
, don't even think about running until after that very last element has either slid up or slid down? 本着更好的编码实践的精神,是否有一种更有效的说法:“嘿,
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.");
}
Thanks in advance! 提前致谢!
jQuery's slide*
functions take a callback parameter that runs on completion: jQuery的
slide*
函数采用在完成时运行的回调参数:
complete
Type: Function()
A function to call once the animation is complete, called once per matched element.complete
Type: Function()
动画完成后调用的函数,每个匹配的元素调用一次。
...
movie.slideDown(updateSearchInfo);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.