Riccardo Romoli
Riccardo Romoli

Reputation: 95

Timer in javascript

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);

Upvotes: 0

Views: 116

Answers (2)

Vasile Alexandru Peşte
Vasile Alexandru Peşte

Reputation: 1308

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";

Upvotes: 1

gyre
gyre

Reputation: 16769

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')

Upvotes: 0

Related Questions