It is necessary to display the result of the script on the page at specified intervals (for example, 1000 ms). There is a function that iterates over objects in the array, and if the condition matches, it displays the characteristics of the object. Actually, the code:

function sleep(ms) { let t = (new Date()).getTime(); let i = 0; while (((new Date()).getTime() - t) < ms) { i++; } } function isNew_Car(obj) { sleep(1000); if (obj.year >= document.getElementById('year').value) { GARAGE_NEW.push(obj); document.getElementById('result').textContent += ` Name: ${obj.name} Year: ${obj.year} Price: ${obj.price} <br> `; console.log(GARAGE_NEW); } } function check_car() { for (let i = 0; i< GARAGE.length; i++) { isNew_Car(GARAGE[i]) } } 

GARAGE stores an array of view objects.

 {name: "Honda", year: 2015, price: 12000} 

The problem is this: the pause in the output of elements to the page is ignored; they are all displayed in an ensemble after the cycle has gone through the entire array. At the same time, for debugging, I tried to output to the console - everything is clear, it is displayed every 1 second, the problem is only with the DOM. Instead of textContent I tried to pass through innerHTML and createElement , the result is the same. Replacing sleep () with setTimeout () also does not have the desired effect. What am I doing wrong and how to fix it?

    1 answer 1

    sleep in this case slows down the whole page and while this function is being performed, neither the cycle goes further, nor the drawing is performed.

    Instead, you need to use setTimeout , for example, setting intervals proportional to the index:

     for (let i = 0; i< GARAGE.length; i++) { setTimeout(()=>isNew_Car(GARAGE[i]), i*1000); } 
    • Indeed it works, thanks. It remains to understand why console.log does not slow down, but drawing slows down, because they work in one iteration. Please do not kick for Noob questions - nyakove
    • @MikhailDykun, for example, because console.log is executed after sleep, and everything is ok, and the drawing will be executed when the check_car is check_car - Grundy