javascript - Simple timer, and setinterval -


What is the best way to create timers in JS?

I am using it by now:

  var sec = 0; Set interval (function () {sec + = 1}, 1000);   

I have seen that, when I need milliseconds, it is very slow, the change in the browser tab completely stops.

  var milisec = 0; SetInterval (function () {millisec + = 1}, 1);   

I'm looking for a better way to handle it, which will continue to work even when the browser window is changed.

With milliseconds, the resolution of the timer is not sufficient. In most cases, callback should be approximately 50 Not more than 250 times will be called, even when you set the interval to 1 mms. Look for an explanation (as specified by Sani Hattunenen).

With 1000ms this will work better. But still when the tab becomes inactive, and when the CPU is busy or any other script is running on your page, the delay may occur.

A solution is not to increase a counter, but to test how much time has passed since the last call of the timer, in this way, time remains correct, even when the delay is delayed Has become or is interrupted in the middle.

This snippet will remember the start date, and at each timer interval, seconds and milliseconds for the difference between seconds, update time and start time.

  var start = new date (); Var millisecond = 0; var seconds = 0; Set interval (function () (var = = new date ()) millisecond = now.gate time () - start.getTime (); seconds = round (millisecond / 1000);), 1000);   

I have set a gap from 1000. You can set it low, but it will cost more.

Related Questions:

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -