Access dynamically created array of items

Asked

Viewed 54 times

0

I have a chronometer that adds images to each "X" seconds and each image is inserted in an array. I want every 4 images (array[3]) the timer to pause and issue an alert

function addImg() {

    const image = document.createElement('img');
    image.src = 'mush.png';
    document.getElementById('mushs').appendChild(image);
    imgList.push(image);
}

The images are being created and correctly inserted in the array according to the chronometer, the condition below does not work

 if (imgList.length == 3){
    pause();
    alert("TAKE A BREAK!");
}
var ms = 0,s = 0,m = 0;
var timer;

var stopwatchEl = document.querySelector('.stopwatch');
var lapsContainer = document.querySelector('.laps');
var imgList = [];

function start() {
    if(!timer){


    timer = setInterval(run, 10);
    }
}

function run(){
    stopwatchEl.textContent = (m < 10 ? "0" + m:m) +":" + (s <10 ? "0"+s:s) +":"+ (ms < 10 ? "0"+ms:ms);
    ms++;
if (ms==100){
    ms = 0;
    s++;
}
if (s ==60){
    s=0;
    m++;
    }
    if (s % 2 === 0 && ms ===00){


        let brk = document.createElement("p");
        brk.innerText = "Take a break!";
        lapsContainer.appendChild(brk);
        addImg();
        pause();
        start();

    }
}
function addImg() {

    const image = document.createElement('img');
    image.src = 'mush.png';
    document.getElementById('mushs').appendChild(image);
    imgList.push(image);
}
function pause(){
    clearInterval(timer);
    timer=false;
}
function stop(){
    clearInterval(timer);
    timer=false;

    ms=0;
    s=0;
    m=0;
    stopwatchEl.textContent = (m < 10 ? "0" + m:m) +":" + (s <10 ? "0"+s:s) +":"+ (ms < 10 ? "0"+ms:ms);
}
function restart(){
    stop();
    start();
}
function lap(){
    if(timer){
        var li = document.createElement("li");
        li.innerText = (m < 10 ? "0" + m:m) +":" + (s <10 ? "0"+s:s) +":"+ (ms < 10 ? "0"+ms:ms);
        lapsContainer.appendChild(li);
    }
}
function resetLaps(){
    lapsContainer.innerHTML = "";
}
if (imgList.length == 3){
    pause();
    alert("TAKE A BREAK!");
}
```HTML
<div class="controls">
        <button onclick="start()">Start</button>
        <button onclick="pause()">Pause</button>   
        <button onclick="stop()">Stop</button>
        <button onclick="restart()">Restart</button>
        <button onclick="lap()">Lap</button>
        <button onclick="resetLaps()">Reset Laps</button>
        <button onclick="addImg()">Add Image</button>


    </div>
    <div class="stopwatch">00:00:00</div>
    <ul class="laps"></ul>

    <div class="toad" id="mushs"></div>

  • the length has to be 4 to start chatting, the position that is start by zero also counts as size. it is good to always assemble a minimum example

  • post the full code

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.