JSFiddle - React, Tailwind, and code Playground
by Alexander
HTML
<button id="stop">Stop</button>
<input type="button" id="start" value="Start">
<input type="number" id="inc" value="1">
<input type="number" id="interval" value="10">
<input type="button" id="dir" value="+">
<select id="method">
<option value="timer">setInterval</option>
<option value="raf">requestAnimationFrame</option>
<option value="css">Add CSS animate</option>
<option value="css2">CSS transform</option>
</select>
<div>Test</div>
CSS
div {
width: 100px;
height: 50px;
background: #f00;
border: 1px solid #00f;
position: absolute;
top: 100px;
left: 0px;
}
input[type=number] {
width: 50px;
}
.animate {
transition: all 2s ease-in-out;
}
.move-right {
transform: translate(300px,0);
}
.move-left {
transform: translate(0,0);
}
JavaScript
console.clear();
var $ = document.querySelector.bind(document);
Element.prototype.on = Element.prototype.addEventListener;
var div = $("div"),
pos = { x: 0 },
timerId,
$dir = $("#dir"),
$interval = $("#interval"),
$inc = $("#inc"),
$method = $("#method");
$dir.on("click", function(){
if (this.value == "+") return this.value = "-";
this.value = "+";
});
$("#stop").on("click", function(){
clearInterval(timerId);
cancelAnimationFrame(timerId);
div.removeAttribute("class");
});
$("#start").on("click", function(){
switch ($method.options[$method.selectedIndex].value ) {
case "timer": move1(); return;
case "raf": move2(); return;
case "css": move3(); return;
case "css2": move4(); return;
}
});
function dirRight() {
return $dir.value == '+';
}
function moveX() {
if (dirRight())
pos.x += parseInt( $inc.value );
else
pos.x -= parseInt( $inc.value );
div.style.left = pos.x + "px";
}
function move1(){
timerId = setInterval(
function(){
//console.log(+new Date);
moveX()
},
parseInt( $interval.value )
);
}
function move2(time) {
//console.log(time);
moveX();
timerId = requestAnimationFrame(move2 /*, связанный элемент elem */);
}
function move3() {
div.setAttribute("class", "animate");
div.style.left = dirRight() ? "300px" : "0";
}
function move4() {
div.setAttribute("class", "move-" + (dirRight() ? "right" : "left") + " animate");
}