Why is this code not working? I'm trying to do a simple timer. I want after pressing a button in HTML, the JavaScript function is triggered, which, through its variables, passes the number of seconds and the diva tag in which it will print the timer. The function should divide the number of the first variable by 60 (getting minutes and seconds in the remainder), write on the page, subtract 1 from the original number and repeat it with a delay of one second until the value of the variable = 0.

I tested this option both before and after writing the condition stopping the function, but it does not work. What's my mistake?

<script> function timer(tag,txt){ document.getElementById(tag).innerHTML+=txt/60 + '<br>'; txt = txt - 1; setTimeout(timer,1000); } </script> <div id="str"></div> <input type="button" onclick="timer('str',800)" value="НаТми мСня" /> 

  • one
    addText - there is no such function. - user190134
  • @ user190134 Sori, ochepyatka, changed the name of the function after the publication, during the test, all the names coincided. - Rumata
  • 2
    setTimeout(function() { timer(tag, txt); }, 1000); - Igor
  • catch errors through the console. - user190134
  • @Igor Thank you so much, it works! - Rumata

2 answers 2

 <!DOCTYPE html> <html> <head> </head> <body> <script> var x='str'; var time=800; function timer(){ document.getElementById(x).innerHTML+=time/60 + '<br>'; time = time - 5; if (time>0) {setTimeout("timer()",100);} else {alert("Computed");} } </script> <div id="str"></div> <input type="button" onclick="timer()" value="НаТми мСня" /> </body> </html> 
  • Thank you very much, very interesting option! I, too, in the end turned out to be a little bit better, but such a task can have many solutions. - Rumata

Why is this code not working?

You call:

 setTimeout(timer,1000); 

But if you want to pass parameters asynchronously, you need to call something like this:

 setTimeout(function(){timer(tag,txt);},1000); 

You can use setInterval here:

 var interval, txt; function timer(tag, txt){ document.getElementById(tag).innerHTML+=txt/60 + '<br>'; }; 
 <div id="str"></div> <input type="button" onclick="txt = 800;interval = setInterval(function(){timer('str', txt--);}, 1000)" value="НаТми мСня" /> <input type="button" onclick="clearInterval(interval)" value="ΠžΡΡ‚Π°Π½ΠΎΠ²ΠΈ мСня" /> 

Do not insert recursion (even if asynchronous) where it is not required - good.

  • Thank you very much, an interesting option! True, in my case, I need the timer to stop itself. And why is recursion not desirable? PS I noticed a strange thing - the delay slows down along with the browser. I wonder if there are more accurate options ... - Rumata
  • It's my pleasure. Worse, less controllable. And about the fact that the timer itself stopped: clearTimeout and clearInterval functions are there. - Goncharov Alexander
  • The setTimeout function after the timeout takes the parameters that will be passed to the callback - Grundy