Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make a set of numbers that increase every 30 seconds to line up in an ascending order?

If you run this javascript code below,

var i = 20220215155;
    function increment(){
     i++;
        document.getElementById('period').innerHTML += i + "<br />" + "<hr />" ;
    }   
    setInterval('increment()', 32100);

you will see that after every 30 seconds, the numbers (20220215155) gets incremented and each increment is printed on a new line. E.g;

**20220215156

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

20220215157

20220215158

20220215159

20220215160**

But I want each print to sort this way after each incrementation;

**20220215160

20220215159

20220215158

20220215157

20220215156**

Whereby if 20220215156 is on the first line, after 30 seconds, 20220215157 should be on the first line and the previous numbers goes to the second line automatically and after the next 30 seconds, 20220215158 appears in the first line and so on. I just hope anyone understands.

Please I need help doing that.

>Solution :

insertAdjacentHTML is useful here. You can use the afterbegin property to add new elements containing the numbers to the top of the container.

const i = 20220215155;
const div = document.querySelector('#period');

// The function accepts a variable (the new number)
function increment(i) {

  // Prepend the number to the container
  div.insertAdjacentHTML('afterbegin', `<div>${i}</div>`);

  // Call the function again with an incremented number
  setTimeout(increment, 1000, ++i);

}

increment(i);
<div id="period"></div>

Additional documentation

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading