Here's what I'm trying to achieve: when a user shakes his device, I want an element on page to rotate CW 20 degrees with every shake and when it reaches maximum of 45 degrees to rotate CCW 20 degrees with every shake, until it reaches -45 deg., and vice versa. I'm using 'shake.js' to detect shake. The problem is it does the rotation, but not animated. The element sort of jumps to the rotation degree. So I tried to achieve the animation effect by using a for
loop with setTimeout', I tried it with
whileloop with setInterval and then I tried it with
setInterval`, but I'm still not able to achieve the animation effect. Here's my code:
var maxDegree = 45;
var minDegree = -45;
var lastDegree = 0;
var totalShakes = 10;
var rotationDegree = 20;
var rotationCounter = 0;
var currentDegree = 0;
var shakeCounter = 0;
var direction = "right";
var box = null;
var info = null
var interval;
window.addEventListener('load', init, false);
function init() {
box = document.getElementById('box');
info = document.getElementById('tilt_info');
window.addEventListener('shake', shakeEventDidOccur, false);
}
function shakeEventDidOccur () {
shakeBox();
}
function shakeBox(){
if(direction == "right") {
currentDegree += rotationDegree;
if(currentDegree >= maxDegree) {
currentDegree = maxDegree;
direction = "left";
}
interval = setInterval(function(){
if(lastDegree < currentDegree){
box.style.webkitTransform = "rotateZ("+ (lastDegree++) +"deg)";
lastDegree++;
}
},100);
lastDegree = currentDegree;
} else {
//...the logic to rotate the box CCW
}
shakeCounter +=1;
info.innerHTML = shakeCounter;
if(shakeCounter >= totalShakes) {
box.style.webkitTransform = "rotateZ(0deg)";
window.removeEventListener('shake', shakeEventDidOccur, false);
}
}
These are my loops I was talking about earlier:
for(var i = lastDegree; i <= currentDegree; i++) {
setTimeout(function(){
box.style.webkitTransform = "rotateZ("+ i +"deg)";
info.innerHTML = "LD: " + lastDegree + "; CD: " + currentDegree + "; i: " + i;
}, 1000);
}
while(lastDegree < currentDegree) {
setTimeout(){
function(){box.style.webkitTransform = "rotateZ("+ (lastDegree+1) +"deg)";
lastDegree++;}, 100
};
}
Why can't I achieve the animation effect?