how could i add a 1 minute timeout to this code before it answers?
//cd test
client.on("message", (msg) => {
if(msg.content.toLowerCase().startsWith(`${PREFIX}1cd`)) {
let user = message.mentions.roles.first();
message.channel.send(`1 minute has passed <#${msg.author.id}>`)
}
});
//cd test
Like this:
setTimeout(() => {
// Code goes here
}, 60000)
See setTimeout()
https://www.w3schools.com/jsref/met_win_settimeout.asp
client.on("message", (msg) => {
if(msg.content.toLowerCase().startsWith(`${PREFIX}1cd`)) {
//pass the code that you want to execute later as a callback function
setTimeout(() => {
let user = message.mentions.roles.first();
message.channel.send(`1 minute has passed <#${msg.author.id}>`)
}, 60000); //60s is 60000 ms, and it takes the amount of time as milliseconds
}
});
Related
I am trying to make an api call (API1) every 2 seconds for a period of 1 minute. During this minute I need to exit the interval if condition is met and do another API call (API2). The problem that I am facing is if the API1 get into a pending state for more than 2 seconds, the second call of API1 will start and again if in pending state for 2 seconds the third call will happen ending up with quite few calls for same api all under pending state …. How can I stop the subsequent calls until the previous call is resolved?
useEffect(() => {
if (triggerTheInterval) {
startInterval()
return () => clearInterval(id)
}
}, [triggerTheInterval])
onClick = () => {
makefirstcallforapi1();
}
//this is only to get the first call at first second - before the 2 seconds interval starts
const makefirstcallforapi1 = () => {
setTimer(new Date().getTime());
fetch(url).then(res => {
if (conditionmet) {
//do the API2 call
} else {
setTriggerTheInterval(true)
}
})
startInterval = () => {
id = setInterval(() => {
fetch(url).then(res => {
if ((new Date().getTime() - startTime > 60000 || condtionmet) {
//do something then exit the interval
}
})
}, 2000)
}
I'm very new to coding so it's probably horrible. Here's the code
let userCooldown = {};
client.on("message", message => {
if (message.content.includes('ping'))
if (userCooldown[message.author.id]) {
userCooldown[message.author.id] = false;
message.reply('Pong');
setTimeout(() => {
userCooldown[message.author.id] = true;
}, 5000) // 5 sec
}
})
the plan would be for the bot not to respond to the message for 5 seconds until it's written again
Not sure why you set the cooldown to false if it's true when someone sends a message and why you set it to true after five seconds.
If your userCooldown includes the users who currently can't execute the function, you need to check if they are already on that list. If they are, don't execute the function. If they are not, execute the function, add them to the list and use setTimeout to remove them after five seconds. Try to run the snippet below:
let userCooldown = {};
function onMessage(message) {
console.log(`onMessage fired with message: "${message.content}"`);
if (message.content.includes('ping')) {
// if user can't execute the fucntion, just exit
if (userCooldown[message.author.id]) return;
// if they can, add them to userCooldown
userCooldown[message.author.id] = true;
console.log('Pong!');
// and remove them after 5 seconds
setTimeout(() => {
userCooldown[message.author.id] = false;
}, 5000);
}
}
// run it every second to test it :)
let message = { content: '!ping', author: { id: 'authorID' } };
setInterval(() => onMessage(message), 2000)
I'm making a setInterval method in my discord bot, but I have an issue in stopping the Interval.
Look at my code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Im online');
});
client.on('message', async msg => {
var interval;
if(msg.content == '!spam')
{
interval = setInterval(() => {
msg.channel.send('test');
}, 2000);
}
if(msg.content.startsWith('!stop'))
{
clearInterval(interval);
}
});
That should definitely work, right?
If you know the answer please help me!!
The problem is:
client.on('message', async msg => {
var interval;
This creates a new variable binding interval every single time the message handler runs. Inside any single message handler, either
interval = setInterval(() => {
msg.channel.send('test');
}, 2000);
will run, or
if (msg.content.startsWith('!stop')) {
clearInterval(interval);
}
will run (or neither will run). But the interval is not persistent outside of the function, so further messages will be attempting to clear a different interval binding.
Make interval persistent instead, and also check that you don't start an interval while one is already going on:
let interval;
client.on('message', (msg) => {
if (msg.content == '!spam' && !interval) {
interval = setInterval(() => {
msg.channel.send('test');
}, 2000);
}
if (msg.content.startsWith('!stop')) {
clearInterval(interval);
interval = null;
}
});
The client sends “true” every 5 seconds. How to execute a function on the server (Node.js) if the request does not arrive within 10 seconds? Please give an answer as an example code
Client:
let time = JSON.stringify({
timeOnSite: true,
});
setInterval(() => {
let xhr = new XMLHttpRequest();
xhr.open('POST', '/time');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(time);
}, 5000);
Server:
app.post('/time', function(req, res){
time += 5;
console.log(time);
res.send('ok');
});
The trick to meeting this sort of requirement is using timeouts.
Each time you receive your message, set yourself a timeout for ten seconds in the future. If a timeout already exists, clear it first.
let tenSecondTimeout
app.post('/time', function(req, res){
if (tenSecondTimeout) clearTimeout(tenSecondTimeout)
tenSecondTimeout = setTimeout (
function() {
/* here, do whatever you want when the timeout fires */
},
10000)
time += 5
console.log(time)
res.send('ok')
});
You can create a Timer class to help you. Create instance once and update on every request. You can pass callback function to execute of time escape.
Timer:
class Timer {
constructor(time, cb) {
this.time = time;
this.cb = cb;
}
update() {
clearTimeout(this.timeId);
this.start();
}
start() {
this.timeId = setTimeout(() => {
this.cb();
}, this.time);
}
}
Start to Init:
const timer = new Timer(100, function print() { // Chnage time to 10000ms
console.log(new Date());
});
timer.start();
Update/ Reschedule:
timer.update();
class Timer {
constructor(time, cb) {
this.time = time;
this.cb = cb;
}
update() {
clearTimeout(this.timeId);
this.start();
}
start() {
this.timeId = setTimeout(() => {
this.cb();
}, this.time);
}
}
const delay = (t) =>
new Promise((r) => {
setTimeout(r, t);
});
async function main() {
const timer = new Timer(100, function print() { // Chnage time to 10000ms
console.log(new Date());
});
timer.start();
await delay(200)
timer.update();
await delay(50)
timer.update();
await delay(50)
}
main()
So im trying to do my discord bot send a message 5 minutes after someone send a command, but when someone use the command it start sending the message every minute, thats the code
client.on('message', function(message) {
if (message.content === "!command") {
var interval = setInterval (function () {
client.channels.get("493228844896092162")
.send("123")
.catch(console.error);
}, 1 * 5000);
}
});
Your interval seems to be incorrect. setInterval expects interval to be in milliseconds.
1 * 5000 -> 5sec
You need to update that to
5 * 60 * 1000 -> 5 mins
setInterval takes the arguments of a function and a set number of milliseconds on which to trigger.
The correct interval would be
setInterval(function(){}, 5 * 60000)
This is 5x60 seconds
I'd code it like this:
client.on('message', function(message) {
if (message.content === "!command") {
var interval = setInterval (function () {
try {
var meme = client.channels.get("493228844896092162")
meme.send("123")
} catch (error) {
console.log(error.stack);
}, 5 * 60000);
}
});