var box = document.getElementById('box'), a1end, a2end, cdend, a3end, a4end, animate1 = setInterval(function() { if (box.style.top === (window.innerHeight - 120) + 'px') { clearInterval(animate1); a1end = true; } box.style.top = ( +box.style.top.replace('px', '') + 1 ) + 'px'; }, 1), animate2 = setInterval(function() { if (box.style.left === (window.innerWidth - 120) + 'px') { clearInterval(animate2); a2end = true; } box.style.left = ( +box.style.left.replace('px', '') + 1 ) + 'px'; }, 1); checkEnd1(function() { box.style.background = 'greenyellow'; box.innerText = 'Next stage starts in 5 seconds'; var i = 4, cd = setInterval(function() { if (!i) { clearInterval(cd); cdend = true; } box.innerText = 'Next stage starts in ' + i + ' seconds'; i--; }, 1000); }); checkEnd2(function() { box.style.background = 'white'; box.innerText = ''; var animate3 = setInterval(function() { if (box.style.left === '20px') { clearInterval(animate3); a3end = true; } box.style.left = ( +box.style.left.replace('px', '') - 1 ) + 'px'; }, 1); }); checkEnd3(function() { var animate4 = setInterval(function() { if (box.style.top === '20px') { clearInterval(animate4); a4end = true; } box.style.top = ( +box.style.top.replace('px', '') - 1 ) + 'px'; }, 1); }); checkEnd4(function() { box.style.background = 'lightcyan'; box.innerText = 'Animation complete'; }); function checkEnd1(fn) { (a1end && a2end) ? fn() : setTimeout(function() { checkEnd1(fn); }, 200); } function checkEnd2(fn) { (cdend) ? fn() : setTimeout(function() { checkEnd2(fn); }, 200); } function checkEnd3(fn) { (a3end) ? fn() : setTimeout(function() { checkEnd3(fn); }, 200); } function checkEnd4(fn) { (a4end) ? fn() : setTimeout(function() { checkEnd4(fn); }, 200); }