0

I have to do a timer in javascript with timing events, the time units should be in milliseconds.

i need something like this:

start_timer //some code.. stop_timer //and then show the ms

sorry for my english, and thank you for help!

edit:

i tried this method as test:

var d = new Date();
    var time =  d.toLocaleTimeString();
    var myVar = window.setInterval(function(time){  time -= d.toLocaleTimeString()
    return code.value = time.toString();
    }, 5000);
1
  • I think OP might mean benchmarking, like console.time(). Commented Apr 9, 2017 at 20:07

2 Answers 2

1

The console.time method is perfect but if you want to keep the result in memory you have to use the Date.now method.

let now = Date.now();

for (let i = 0; i < 100000; ++i)
    // ...

// Result in milliseconds.
let result = Date.now() - now;

// If you want to show it in a input box.
input.value = result + "ms";
Sign up to request clarification or add additional context in comments.

2 Comments

what's let syntax?
@RiccardoRomoli ES6 syntax its pretty much the new var to understand a little more read into javascript hoisting.
0

You can use console.time(), for the browsers that support it:

console.time('Stuff')

for (var i = 0; i < 1000; i++) {
   // run some code
}

console.timeEnd('Stuff')

3 Comments

Forgive my ignorance, I just started, it is normal that each time you start, the time change?
Yes; there are many factors that can influence run time on a machine and thus the numbers logged are rarely consistent. They will start to appear more logical if you place some actual code where I had // run some code.
how can i implement the result on a input box in my html? if you see the code i've posted i need to set "code.value" as the result of timer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.