Reputation: 347
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()
). 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.
I presume this is because I'm dealing with a couple of hundred $(".movie")
elements (although I don't really know).
setTimeOut()
works okay but it seems inelegant, both in terms of coding and performance on the page (the text updates after a delay). 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?
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!
Upvotes: 0
Views: 347
Reputation: 21708
jQuery's slide*
functions take a callback parameter that runs on completion:
complete
Type: Function()
A function to call once the animation is complete, called once per matched element.
...
movie.slideDown(updateSearchInfo);
...
Upvotes: 3