Create an accurate millisecond timer that loops in Javascript
You could use a .setTimeout()
at the end of your code to restart your .setInterval()
, after the desired time has passed
function runInterval (loopAfter) { var startTime = Date.now();
var interval = setInterval(function() { var elapsedTime = Date.now() - startTime; var time = (elapsedTime / 1000).toFixed(3); console.log(time); }, 10); setTimeout(() => { clearInterval(interval); runInterval(loopAfter); }, loopAfter);}
runInterval(5000);
How to create a second/millisecond timer like phone?
I don't know what are you trying to do but i did some modification of your code which makes it a bit more interesting and clean ...
public class Mathgame {
// it is not necessary do it static
public int secondsPassed = 0;
//alternatively you can use Timer timer = new Timer(true); if you want to stop timer immediately after method main is finished
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
secondsPassed++;
// your timer will run this method every 1 sec, so you need to put output here if you want to see changes
System.out.println("Running my task again. secondsPassed is " +secondsPassed);
}
};
public void start() {
//this timmer will run your task every 1000ms (1 second) and will start in 1000ms (1 second) after start is called
timer.scheduleAtFixedRate(task, 1000, 1000);
}
// this is main method so it is better to throw exceptions upper then handler them without output
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to 'The Math Game!' Please chose whether you would like to play or not by inputting 'yes' or 'no'.");
String x = input.nextLine();
// it is better to check for 'yes' than for 'no' this is good practice
if (x.equalsIgnoreCase("yes") || x.equalsIgnoreCase("y")) {
System.out.println("OK! We are starting the game in...");
System.out.println("3");
Thread.sleep(1000);
System.out.println("2");
Thread.sleep(1000);
System.out.println("1!!");
Thread.sleep(1000);
System.out.println("Go!");
//starting your timer, we have to create object of your class first and then run method start
Mathgame mathgame = new Mathgame();
mathgame.start();
System.out.println("Your timer started!");
//main is finished however there is timer thread which is still working
// if you want to stop timer immediately after main then you need to build it as 'Timer timer = new Timer(true);'
// in that case you may put here extra sleep and see how timer is working
//let wait until timer will count 10 sec
Thread.sleep(10000);
//you can check secondsPassed from main too
System.out.println("This is called from main. secondsPassed value is " + mathgame.secondsPassed);
System.out.println("Method main is finished");
}
}
}
JavaScript stopwatch being slower than expected
Since you can't guarantee how long the code inside the interval will take to run, it's better to use the Date
api. Instead of relying on the interval, you could run a loop that constantly calculates the ms between now and the start.
Here's an example of this concept:
// assume this runs when the stopwatch starts
let startTime = new Date().getTime()
// this should stop when the user stops the timer, but I'm using a for loop
// for the example
for(let i = 0; i < 100; i++) {
let now = new Date().getTime()
console.log("ms elapsed: " + (now - startTime))
}
Now it doesn't matter how fast the code is; it should always be accurate.
Adding milliseconds to my Javascript stopwatch
Adding milliseconds to your existing code is fairly straight forward. You only need to follow the basic pattern you have established. The only real difference is that you're measuring by 1000 instead of by 60.
What changed:
- Added new var
milli
- Changed the "frequency" of
timer
to 10 milliseconds (1 millisecond seemed a bit of an overkill) - When the
Add
function executes we add 10 milliseconds tomilli
- Added the milliseconds to the end of your current display
Update
What changed:
- Set
t
tonull
in the "stop" buttononclick
function. - Changed the
onclick
of the start button to a function rather than pointing it attimer
. Now we can checkt
and if it does not have a value we run the timer. This stops additional clicks on the start button from running more timers so we don't get "extra" calls toadd
. - Added ".000" for the milliseconds in the
time
element (I missed this in my first version). - Added the default ".000" to the displayed value in the "clear" function (I missed this in my first version).
- Added
milli = 0;
in the clear function (I missed this in my first version).
var h1 = document.getElementsByTagName('h1')[0], start = document.getElementById('start'), stop = document.getElementById('stop'), clear = document.getElementById('clear'), milli = 0, seconds = 0, minutes = 0, hours = 0, t;
function add() { milli += 10; if (milli >= 1000) { milli = 0; seconds++; if (seconds >= 60) { seconds = 0; minutes++; if (minutes >= 60) { minutes = 0; hours++; } } } h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds) + "." + (milli > 90 ? milli : "0" + milli);
timer();}function timer() { t = setTimeout(add, 10);}timer();
/* Start button */start.onclick = function() { if(!t) timer();}
/* Stop button */stop.onclick = function() { clearTimeout(t); t = null;}
/* Clear button */clear.onclick = function() { h1.textContent = "00:00:00.000"; milli = 0; seconds = 0; minutes = 0; hours = 0;}
<h1><time>00:00:00.000</time></h1><button id="start">start</button><button id="stop">stop</button><button id="clear">clear</button>
Cross platform millisecond timer lasting more than 49 days?
Use a 64bit integer, presuming that gives you enough time
You are correct; there is no standard. One possibility would be to use the Boost DateTime library, alternately find another or roll your own.
Good Luck!
Related Topics
Prefix(_ Maxlength:) Is Type-Erased When Used with a Struct That Conforms to Lazysequenceprotocol
iOS Charts - Single Values Not Showing Swift
A Warning "'Init()' Is Deprecated". [Swift, iOS App, Learning Model]
Swift Spritekit Get Visible Frame Size
Heightanchor.Constraint Not Change Height of View
How to Change/Modify The Displayed Title of an Nspopupbutton
Pdf417 Decode and Generate The Same Barcode Using Swift
Cleanly Handling /Usr/Local/ with Swift Package Manager and Libevent
Combining Scenekit and Spritekit in a Single Screen
Swift Pattern Match on Array<Any>
Macos, Swift 3: How to Get Data Back After Segue
Swift Running Code in Periodically Background
Abstract Class and Abstract Function in Swift
Arkit - Place a Scnplane Between 2 Vector Points on a Plane in Swift 3