Q:

Check if the time difference is less than 1 second in moment

In my javascript project, I want to check if the time difference is less than 1 second. I use moment to get this difference. This is the function I have written to achieve it.
const withinOneSecond = (time) => {
  const currentTime = moment();
  return time + 1000 < currentTime;
};

But this doesn't work as expected. How can I check if the given time is within a second to the current time?

A:

You can use moment#diff.
As an example, I've added a second to a date and taking the difference in with .diff passing seconds as second argument should return the difference in seconds

var a = moment();
var b = moment().add(1, 'seconds');
console.log(b.diff(a, 'seconds'))
<script src="https://momentjs.com/downloads/moment.js"></script>

The supported measurements are years, months, weeks, days, hours, minutes, and seconds. Here
For your particular case, you should be doing something like

const withinOneSecond = (time) => {
  const currentTime = moment();
  return currentTime.diff(time, 'seconds')  == 1
};

var time = moment().add(1, 'seconds');
let results = withinOneSecond(time);

console.log(results);
<script src="https://momentjs.com/downloads/moment.js"></script>

