How to report elapsed time between two events in js?

kflak's icon
Max Patch
Copy patch and select New From Clipboard in Max.

I'm starting (finally!!!) to get the hang of js in max, and want to port some of the max code to javascript. Question: how do I perform an operation equivalent to the timer max object? Basically the behavior I want to duplicate is this:

do.while's icon

Hello !
i believe that you could take advantage of Date object .

var t0 = 0 ;
var time = new Date();
var msg_int = function(i){
    if(i == 1){
        t0 = time.getTime();
    }else{
        var t1 = time.getTime() - t0 ;
        post(t1);
    }
}

I hope it works as ive typed it from my assumption . Cant check it for the moment . let me know if that suits your needs .
here is the link to Date object description : http://www.w3schools.com/jsref/jsref_obj_date.asp

kflak's icon

Thanks, do...while! Yeah, I tried something along those lines, and it seems like that would be the way to go. However, the only output I'm getting is 0 every time I toggle from 1 to 0. Can't quite get my head around why this happens, as the code makes perfect sense....

do.while's icon

oh . try

new Date().getTime() ;

on every event .

var t0 = 0 ;

var msg_int = function(i){
    if(i == 1){
        t0 = new Date().getTime();
    }else{
        var t1 = new Date().getTime() - t0 ;
        post(t1+"\n);
    }
}

kflak's icon

Sweet, that works! Thanks a heap!

do.while's icon

great ! have fun !