Home > front end >  To solve, these two simple animation of writing which is more efficient, for simple reasons why
To solve, these two simple animation of writing which is more efficient, for simple reasons why

Time:10-11

<body>



<script>
Var BTN=document. GetElementById (" BTN ");
Var btn1=document. GetElementById (" btn1 ");

Var box=document. GetElementById (' box ');
Var box1=document. GetElementById (" box1 ");

BTN. Onclick=function () {
The animate (box, 800);
The animate (box1, 800);
}

Btn1. Onclick=function () {
The animate (box, 400);
The animate (box1, 400);
}

The function the animate (element, target) {
If (element. TimerId) {
ClearInterval (element. The timerId);
TimerId=null;
}

Element. The timerId=setInterval (function () {

Var step=10;

Var current=element. The offsetLeft;

If (current & gt;={target)

ClearInterval (element. The timerId);

Element. Style. Left=target + 'px';
return;
}
The current +=step;
Element. Style. Left=current + 'px';
}, 30);
}
</script>



-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Var btn1=document. GetElementById (" btn1 ");
Var btn2=document. GetElementById (" btn2 ");
Var box1=document. GetElementById (" box1 ");
Var box2=document. GetElementById (' box2 ');

Btn1. Onclick=function () {
The animate (box1, 200);
}

Btn2. Onclick=function () {
The animate (box2, 300);
}

The function the animate (element, traget) {
If (element. TimeId is) {
ClearInterval (element. TimeId is);
TimdId=null;
}

Element. TimeId is=setInterval (fn, 30);
Var current=element. The offsetLeft;

The function fn () {
var speed=10;
The current=current & gt; Traget? Current: the current +=speed;
Element. Style. Left=current + 'px';
}
}

CodePudding user response:

Use requestAnimationFrame is more efficient, you try

CodePudding user response:

reference 1st floor cn00439805 response:
requestAnimationFrame is more efficient, you try


Brother I just contact with JS before long you said this is the H5, I haven't learned that,

CodePudding user response:

After the second element to reach the target location in the timer has been run, belongs to the waste of resources,

CodePudding user response:

reference 3 floor sky waves reply:
element in 2nd timer still runs after reach the target location, belongs to the waste of resources,


Thank you!!!!!!
  • Related