There is a simple code:

<div id="r">0</div> <button id="b" onclick="inc()"></button> <script> function my_click(){ document.getElementById("b").click(); } my_click(); function inc(){ var val = parseInt(document.getElementById("r").innerHTML); val++; document.getElementById("r").innerHTML = String(val); my_click(); } </script> 

But, for some strange reason, inc () only works once. That is, in the diva appears 1, and no more. What am I missing?

  • and what does this code do? +2 to the number adds when you press the button? - Aliaksandr Pitkevich
  • When the page loads, it executes my_click () and then inc (). And inc () increases the value in diva by 1 and causes a click, which then again calls inc (). A kind of recursion. But for some reason it does not work. - DenisKornienko
  • inc() works only when a button is pressed, increases by 1 val and then calls my_click() . As a result, with a single click on the button, the val increases by 2, right? - Aliaksandr Pitkevich
  • And there is. But why does it work only once? And how to do it the way I wanted? - DenisKornienko
  • Honestly, until I can’t figure out what you’re trying to do, maybe when you press the button once, did the number start adding for a while? or how? - Aliaksandr Pitkevich

2 answers 2

Well, as an option to add setInterval

 function my_click(){ document.getElementById("b").click(); } my_click(); function inc(){ setInterval(function () { var val = parseInt(document.getElementById("r").innerHTML); val++; document.getElementById("r").innerHTML = String(val); my_click() }, 100) } 

How fast to add, decide for yourself of course)

  • What you need, thank you. - DenisKornienko

If there is no point and you just need a call stack, then I ask:

 function my_click() { document.getElementById("b").click(); inc(); }; my_click(); function inc() { var val = parseInt(document.getElementById("r").innerHTML); val++; document.getElementById("r").innerHTML = String(val); my_click() }