Home > Blockchain >  calling another function after finishing button click function in jQuery
calling another function after finishing button click function in jQuery

Time:01-31

I want to call a function named func2 after the button click function finished its operations using jQuery. I'm using this method but doesn't work. it calls the button click function on load time.

$("#btn-click").click(function(){
  //do something
});

function func2() {
  //do something
}

    $.when( $("#btn-click").click() ).done(function() {
       func2();
    });

CodePudding user response:

Here is one way to do it: You define an action for the button click. In my example I created a promise with a setTimeout() call. This could be an Ajax call or anything else (not necessarily returning a promise). As soon as the action is done or the promise fulfilled, func2 will step into action.

$("#btn-click").click(func1);

function func1(){
  console.log("func1 started...");
  $.when(new Promise(res=>
setTimeout(res,1000)))
   .then(()=>{
     console.log("func1 done.");
     func2()});
} 

function func2() {
  console.log("func2");
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<button id="btn-click">click</button>

  •  Tags:  
  • Related