Question:
When the page loads, the spacing starts right. I put a button to pause the interval, but it doesn't work as it should.
When you click on the button, there is a pause, but only for a certain period of time, but there should be a complete pause until I click on start. What is the problem?
When the page loads, the interval should start immediately. I wrote this, but I do not know if it is correct.
I ask you not to change the code if there is no great need. If the code has been changed, please comment, and if not difficult, then explain where the incorrect code is.
Thank you.
Use JS only
(function() {
var elem, startInterval, removedElem, widthBlock,
btn1 = document.getElementById('click1'),
btn2 = document.getElementById('click2'),
collectionBlocks = document.getElementById('collection_divs');
function clearThisInterval() {
if (thisElem.clientWidth == 0) {
removedElem = collectionBlocks.removeChild(collectionBlocks.children[0]);
collectionBlocks.appendChild(removedElem);
thisElem.style.width = '150px';
clearInterval(startInterval); //удаляем интервал
// для следующего блока
}
}
function minWidth() {
thisElem = collectionBlocks.children[0];
widthBlock = thisElem.clientWidth;
// Уменьшаем ширину
if (widthBlock != 0) {
startInterval = setInterval(function() {
thisElem.style.width = [widthBlock -= 2] + 'px';
}, 30);
}
setTimeout(clearThisInterval, 2253); // 15 строка //удаляем интервал
}
// Запускаем интервал / строка 19
btn2.onclick = function() {
setInterval(minWidth, 3000);
}
//становить или пауза интервала для уменьшение ширины / 23 строка //
btn1.onclick = function() {
clearInterval(startInterval);
}
//при загрузке стартует сам
//setInterval(minWidth, 5000);
})();
.div {
width: 150px;
height: 30px;
background-color: red;
float: left;
margin-right: 2px;
margin-bottom: 10px;
margin-top: 10px;
}
button {
width: 100px;
height: 40px;
}
<button id="click1">stop</button>
<button id="click2">start</button>
<div id="collection_divs">
<div class="div">1</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">3</div>
</div>
Answer:
If some code that starts the timer is called more than once, it must remember the value returned by setInterval
and call clearInterval
with that value before calling setInterval
.
function minWidth() {
thisElem = collectionBlocks.children[0];
widthBlock = thisElem.clientWidth;
// Уменьшаем ширину
if (widthBlock != 0) {
clearInterval(startInterval); // !!!
startInterval = setInterval(function() {
thisElem.style.width = [widthBlock -= 2] + 'px';
}, 30);
}
setTimeout(clearThisInterval, 2253); // 15 строка //удаляем интервал
}
var minWidthInterval;
// Запускаем интервал / строка 19
btn2.onclick = function() {
clearInterval(minWidthInterval); // !!!
minWidthInterval = setInterval(minWidth, 3000);
}
//становить или пауза интервала для уменьшение ширины / 23 строка //
btn1.onclick = function() {
clearInterval(minWidthInterval); // !!!
clearInterval(startInterval);
}