how does before & after save work

I created custom form. Connected it to data collection. On SUBMIT the data gets posted to the database and I get a pop up saying thank you, as created in the submit button field.

Now I want to add a spinner before the data is saved to the database. On SUBMIT, I want beforeSave() to trigger showing spinner and pop-up to appear afterSave().
Following thing I did.

export function submitButton_click(event) {
$w("#dataset1").onBeforeSave( () => {
//      $w('#group1').show()
//      $w('#box1').show()
//      $w('#image1').show()
//          console.log("Continuing save");
//  } );

//  $w("#dataset1").onAfterSave( () => {
//          console.log("After save")
//      $w('#group1').hide()  
//          $w('#box1').hide()
//          $w('#image1').hide()
//  });
}

This worked but even if the input data has some error, onBeforedSave() fn gets triggered. When I keep onBeforeSave() and onAfterSave() out of the submitButton_click() the errors are captured but then directly thank you banner pop ups spinner doesn’t get loaded. I would like to know what’s going on behind the scene. I am not a coding expert but i can work with JS but i am not able to understand the WIX api. Can somebody please help me.