Home > Back-end >  How can I make a set of numbers increase every second and for each increment, print the current set
How can I make a set of numbers increase every second and for each increment, print the current set

Time:02-14

I have these set of 11 numbers that increase per second, but I want each increment or the current set of numbers to write on a new line. E.g;

20220215155

20220215156

20220215157 etc...

I tried adding the n tag buh it returned an error.

var i = 20220215155
    function increment() {
    i ,   </n>;

document.getElementById('test').innerHTML = i
     }
  ('increment()', 1000);

Please I really need help as I have been trying to get this for so long.

CodePudding user response:

Your code is not valid JS

Here is something that does work - I am using setInterval here

var i = 20220215155

function increment() {
  i  ; // increment
  document.getElementById('test').innerHTML  = i   "<br/>"; // add it with a breakline
}
setInterval(increment, 1000);
<div id="test"></div>

You can use a template literal for the string too

`${i}<br/>`

CodePudding user response:

You can use setTimeout to call the function after a set time while also increasing the number you initially pass into the function.

// Cache the element
const test = document.querySelector('#test');

let n = 20220215155;

// `increment` accepts `n` as an argument
function increment(n) {

  // Add a new HTML string to the element
  test.innerHTML  = `${n}</br>`;

  // Call the function again with an new `n`
  setTimeout(increment, 1000,   n);
}

increment(n);
<div id="test"></div>

Additional documentation

  • Related