Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Can you reuse Date() objects?

Is it possible to create a new Date() object to get the current date, and then later, after a certain period of time, reuse the same Date() object to get the new current time?

It appears that you have to create a new Date object everytime you want the current date/time.

In my particular application I'm wanting to run an animation and for every single frame of the animation I need to aquire the current time. So creating a new Date object every single frame (potentially for 1000's of frames?) is just going to boost memory usage over time.

Any clues on this one?

like image 814
Jake Wilson Avatar asked Oct 13 '11 04:10

Jake Wilson


People also ask

How does JavaScript Date object work?

The Date Object. The Date object is a built-in object in JavaScript that stores the date and time. It provides a number of built-in methods for formatting and managing that data. By default, a new Date instance without arguments provided creates an object corresponding to the current date and time.

What is date () JavaScript?

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.

How many ways we can create Date object in JavaScript?

There are four different way to declare a date, the basic things is that the date objects are created by the new Date() operator. Example: new Date(): Parameters: The Date() constructor creates a Date object which sets the current date and time depend on the browser's time zone.

Do JavaScript has date data type?

JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.


2 Answers

Unless you're storing them separately, your date objects are garbage collected automatically. Moreover you can create store the current date to the same variable every iteration and not have to worry about memory blooming.

For example:

var current = new Date()
for (var idx = 0; idx <= frameCount; ++idx) {
    current = new Date();

      // Do processing...
}

You do not use more and more memory in this case because the old date will be garbage-collected after it has been overwritten.

like image 109
Wyatt Avatar answered Oct 19 '22 17:10

Wyatt


If you don't actually want the date, but rather the time in milliseconds, use Date.now() so you don't have to create a Date object.

var t = Date.now(); // 1318479105311

You can shim it into older browsers with:

if( !Date.now ) Date.now = function(){ return +(new Date); };
like image 36
user113716 Avatar answered Oct 19 '22 19:10

user113716