Search code examples
javascriptjqueryasynchronouspromisedeferred

Execute code only after a non-thenable, asynchronous function completes


I want to execute my code only after flexslider() function completes. The problem is that flexslider() does not return a promise or other thenable.

So I applied this nasty workaround with setTimeout that I want to get rid of. How can I refactor this and execute my code only after flexslider is initialized?

(function($) {
    $('.flexslider').flexslider({
        animation: "slide",
        controlNav: false
    });
    setTimeout(function() {
        var $navBar = $('.primary-nav');
        var navbarPosition = $navBar.offset().top;
        $(window).scroll(function() {
            var scrollPosition = $(this).scrollTop();

            if (scrollPosition >= navbarPosition) {
                $navBar.addClass('navbar-fixed');
            } else {
                $navBar.removeClass('navbar-fixed');
            }
        });
    }, 1000);
})(jQuery);   

Solution

  • How about using start:

    $('.flexslider').flexslider({
      animation: "slide",
      controlNav: false,
      start: function(){
        // do something....
      }
    });
    

    Documentation