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

Time:02-18

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

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.

CodePudding user response:

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

CodePudding user response:

let info = document.getElementById('info');
let num = 20220215155;

setInterval(() => {
    let newElement = document.createElement('p');
    newElement.innerText =   num;
    info.insertBefore(newElement, info.childNodes[0]); //Adding newElement at the beginning of the parent
}, 1000);
<html>
  <body>
    <div id="info">
      </div>
  </body>
</html>

  • Related