Добрый день, подскажите как организовать код таким образом что бы при нажатии на кнопку 'stop' таймер очищался.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<title>Документ без названия</title>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
background-color: blue;
}
.wrapper {
position: relative;
width: 400px;
height: 400px;
border: 3px solid red !important;
}
.btn-block {
padding: 10px;
background-color: grey;
margin-top: 10px;
}
button {
margin-bottom: 10px;
margin-top: 10px;
width: 100px;
height: 40px;
background-color: yellow;
border: none;
}
</style>
</head>
<body>
<button class="btn">Animate</button>
<button class="btn">Stop</button>
<div class="wrapper">
<div class="box"></div>
</div>
<script>
let box = document.querySelector('.box'),
but = document.querySelectorAll('.btn');
function animate (e){
let id,
count = 0;
function position(){
if(count === 300){
clearInterval(id)
box.style.top = 0 + 'px';
box.style.left = 0 + 'px';
} else{
count++;
box.style.top = count + 'px';
box.style.left = count + 'px';
}
}
if(e.target.lastChild.data === 'Animate'){
id = setInterval(position,10);
}
if(e.target.lastChild.data === 'Stop'){
console.log('Stop')
clearInterval(id);
}
}
for(let i = 0; i < but.length; i++){
but[i].addEventListener('click', animate);
}
</script>
</body>
</html>