Augux
Augux

Reputation: 55

How to make a command time counter

My question is: how can I make a command clock (when you execute !count and after 4 minutes you type !time and it says 4 minutes!) in discord.js

const Discord = require('discord.js');

exports.run = (client, message) => {
  var af = 0;

  a = setInterval(function(){
  console.log("Hi");
  af = af+1;

   if(af == 25){
     clearInterval(a);
  }
  console.log(af);
  }, 60000);
};

exports.help = {
  name: 'time',
  description: 'time?',
  usage: 'time'
};

Upvotes: 2

Views: 3307

Answers (1)

Federico Grandi
Federico Grandi

Reputation: 6806

I would do it like this: when you execute !count you save the server time, when you execute !time you send back the difference between those two dates.

Pseudo-code:

var date;

if (command == 'count') {
  date = new Date();
  message.reply("Done");
}

if (command == 'time') {
  let result = require('pretty-ms')(date ? (new Date() - date) : 0);
  message.reply(result);
}

I'm using the pretty-ms npm package to format milliseconds: docs & live demo.

When someone calls !count, store the current Date somewhere. new Date() - date will give you the difference between the current time and the time you stored, in milliseconds.
Please note that if the commands are in different files, as it seems by the code you posted, you'll need to store the date in a location accessible to both files: one of the solutions is to store the date as a global variable.

// by '...' I mean that you can put it wherever you want in the global object
global['...'].date = new Date():
new Date() - global['...'].date

Edit: Date class explanation
When you create a new Date, it saves the time at the moment you create it. It's like saying "!count was executed at 04:20". When you want to check how much time has passed, you need to calculate the first date minus the current date: "!count was executed at 04:20. Now it's 05:40, so the difference is 05:40 - 04:20 = 01:20: it's 1 hour and 20 minutes since you first executed !count". That translates to new Date() - past_date = time_passed.
Since dates are stored in milliseconds that difference is in milliseconds: if you want to make it more readable, you can format it by using a function as the 'pretty-ms' package, or similar ones.
The key concept is:

  • When !count is called, you save a new Date() to lock that point in time
  • When !time is called, you get the difference by doing new Date() - past_date

Upvotes: 2

Related Questions