获取以毫秒为单位的时间差:Javascript

获取以毫秒为单位的时间差:Javascript,javascript,Javascript,我对javascript很陌生。我试图以毫秒为单位获取特定事件的持续时间。经过一些研究后,我简单地创建了两个日期变量,并将其绑定到窗口,得到了差异。但我得到的时差是0,这不可能是真的。你能告诉我我做错了什么吗?下面给出了相关的代码片段 case "discharge": window.timeStart = new Date(); console.log("---A---===>>>" + window.timeS

我对javascript很陌生。我试图以毫秒为单位获取特定事件的持续时间。经过一些研究后,我简单地创建了两个日期变量,并将其绑定到窗口,得到了差异。但我得到的时差是0,这不可能是真的。你能告诉我我做错了什么吗?下面给出了相关的代码片段

case "discharge":
                window.timeStart = new Date();
                console.log("---A---===>>>" + window.timeStart);

                window.onload = function () {
                    window.timeStop = new Date();
                    window.timedef = window.timeStop-window.timeStart
                    console.log("---B---===>>>" + window.timeStop);
                    console.log("---DIFF---===>>>" + window.timedef);
                };

                //that.showLoadingIndicator();

                if (App.getInstance().getConfig().activeConfiguration == configurations.MultiFlow) {
                    that.currentProcessHandler = new measurementDischargeHandler();
                    window.onload();
                }
                else {

                    that.currentProcessHandler = new dischargeHandler();
                }

你得到差异的方式很好。获取timeStart值后立即调用window.onload,请参见***注释:

window.timeStart = new Date(); // *** Getting the start

window.onload = function () {
    window.timeStop = new Date();
    window.timedef = window.timeStop-window.timeStart
    console.log("---B---===>>>" + window.timeStop);
    console.log("---DIFF---===>>>" + window.timedef);
};

//that.showLoadingIndicator();

if (App.getInstance().getConfig().activeConfiguration == configurations.MultiFlow) {
    that.currentProcessHandler = new measurementDischargeHandler();
    window.onload(); // *** *Calling* window.onload
}
else {

    that.currentProcessHandler = new dischargeHandler();
}
事实上,这完全有可能,很可能在获取timeStart和timeEnd之间没有经过完整的毫秒

不清楚为什么要使用window.onload,但这就是为什么在时间值上看不到任何差异


旁注:在代码中没有理由为窗口指定属性,只需使用局部变量。

如果它表示0,则表示为0。您的代码没有问题。为什么您认为零是错误的?请尝试使用Windows。性能。。。它的精度为亚毫秒。@Isuru:该代码中没有在两个测量点之间呈现屏幕。还有一个GetMillicles方法,它返回指定日期和时间的0到999毫秒,您可以使用。谢谢您的解释!发现我没有在应该叫它的地方叫它。再次感谢各位: