You can pad the number of milliseconds with two zeros (to ensure that there are at least three digits) and then use String.prototype.slice()
to get only the last 3 characters (digits).
var msecs = ('00' + myDate.getMilliseconds()).slice(-3);
That way, even if the number of milliseconds returned is already three digits long, the zeros added as padding will be stripped when you slice()
the string passing -3
as the argument:
// when the number of milliseconds is 123:
myDate.getMilliseconds() === 123
'00' + myDate.getMilliseconds() === '00123'
('00' + myDate.getMilliseconds()).slice(-3) === '123'
// or, when the number is 0:
myDate.getMilliseconds() === 0
'00' + myDate.getMilliseconds() === '000'
('00' + myDate.getMilliseconds()).slice(-3) === '000'