Javascript clearInterval() Stop animation

Description

Javascript clearInterval() Stop animation

View in separate window


<!DOCTYPE html>
<head>
<title>interval and anonymous function</title>
<style>
#redbox//w  w  w .  j av  a  2s .com
{
  position: absolute;
  left: 100px;
  top: 100px;
  width: 200px; height: 200px;
  background-color: red;
}
</style>
<script>

let intervalId=null;

window.onload=function() {
  document.getElementById("redbox").onclick=stopStartElement;
}
function stopStartElement() {
    if (intervalId == null) {
       let x = 100;
       intervalId=setInterval(function() {
                              x+=5;
                              let left = x + "px";
                              document.getElementById("redbox").style.left=left;}, 100);
    }  else {
       clearInterval(intervalId);
       intervalId=null;
    }
}

</script>
</head>
<body>
<div id="redbox"></div>
</body>
</html>



PreviousNext

Related