background

When doing an H5 project, there is a requirement: if the user does not check the protocol when clicking the “OK” button, a jitter animation will be added to the protocol to attract the user’s attention and remind the user that the protocol needs to be checked. However, when realizing this effect, we found that after clicking the “OK” button and shaking once, we did not check the protocol and directly clicked the “OK” button again, the shaking effect would not be present. It turns out that the name of the class to which the animation was added is still there after the first time, so there is no jitter effect after clicking on it. So setTimeout() and clearTimeout() come to mind


SetTimeout (); clearTimeout();

SetTimeout () definition and usage

Definition:

The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds.

Grammar:
setTimeout(code,millisec)
Copy the code
parameter describe
code A necessity. The string of JavaScript code to execute after the function to be called.
millisec A necessity. The number of milliseconds to wait before executing code.


ClearTimeout () definition and usage

Definition:

The clearTimeout() method cancels timeout set by the setTimeout() method.

Grammar:
clearTimeout(id_of_settimeout)
Copy the code
parameter describe
id_of_settimeout ID value returned by setTimeout(). This value identifies the block of code to cancel deferred execution.


Then let’s look at the solution of the project:

Here’s what the code does


Here is the implementation code

  • HTML code:
<div class="pact" >
    <span :class="[check?'pact__check-on pact__check': 'pact__check']" @click="checkAction()"></span>
    <span class="pact__text">You have read and agree</span>
    <a :class="[make_shake?'pact__text-color shaking_animation':'pact__text-color']" href="#">Test Agreement</a> 
</div>
Copy the code
  • The CSS code:
.shaking_animation{
    animation-duration: 300ms;
    animation-iteration-count: 2;
    animation-name: move;
}
@keyframes move {
    from {
        transform: translateX(0px); 25%} {transform: translateX(-16px); 50%} {transform: translateX(0px); 75%} {transform: translateX(16px);
    }
    to {
        transform: translateX(0px); }}Copy the code
  • Js code:
authClick: function(){
    var self = this;
    if(this.check){
        self.make_shake = false;
    }
    else{
        self.make_shake = true
        let timeout = setTimeout((a)= >{
            self.make_shake = false;
            clearTimeout(timeout)
        },300)}}Copy the code

To do this, set a timer, and after 300 milliseconds, reset make_shake to false. After 300 milliseconds, we remove the shaking_animation class name. Then empty the timer.

Conclusion:

Forgive me if I don’t write well. END!!!!!!