Change setGame text every 10 minutes - javascript

I'm trying to do something on the Discord Bot I want to change the setGame text every 10 minutes
For example, 10 minutes later, "#StayHome" => client.user.setGame(#StayHome);
or again after 10 minutes "!watch" = > client.user.setGame(!watch);
I want it to change the setGame text I want every 10 minutes. how can I do that ?
client.user.setStatus("online");
client.user.setGame(`!help`);

const bot = () => {
let status = ["!help", "!watch", "#StayHome"];
let index = 0;
let interval = setInterval(() => {
client.user.setStatus("online");
client.user.setGame(status[index]);
index++;
if (status.length === index) clearInterval(interval);
}, 1000 * 60 * 10);
};
bot();

You can use a setInterval() function and repeat it each 600000 ms (10 minutes).
let currentActivity = 0
let maxActivity = 3
setInterval(async () => {
currentActivity++;
if (currentActivity > maxActivity) {currentActivity = 0};
switch(currentActivity) {
case 0:
client.user.setStatus("online");
client.user.setGame(`!command`);
break
case 1:
client.user.setStatus("online");
client.user.setGame(`!hello`);
break
case 2:
client.user.setStatus("online");
client.user.setGame(`something`);
break
case 3:
client.user.setStatus("online");
client.user.setGame(`!help`);
break
};
}, 600000);
Using a switch statement you can change the status each 10 minutes.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

Related

While loop not stoping with random number

i'm trying to generate random number between 0 and 10, but loop is not stops when it came to 10
function testNumber () {
let i = (Math.floor(Math.random() * 10)+1)
while (i < 10) {
setInterval(() => {
document.write("Random number: " + (Math.floor(Math.random() * 10)+1)
)},1000)
return i;
}
}
function test() {
testNumber();
}
I'm not sure I understood your question, but if I did, you want to keep generating random numbers less or equal to 10, until you get 10 and show them in HTML. This is the solution for that:
HTML:
<div class="num"> </div>
JS:
const num = document.querySelector('.num');
function testNumber () {
let i = (Math.floor(Math.random() * 11)
while (i !== 10) {
num.innerHTML = `${num.innerHTML}Random number: ${i}<br>`
i = (Math.floor(Math.random() * 11)
}
}
If you want to "stop generating random numbers when you get 10", you'll probably want something like this:
function testNumber() {
let counter = 0
while (counter < 10) {
setInterval(() => {
document.write("Random number: " + (Math.floor(Math.random() * 11))
)},1000)
counter++;
}
}
testNumber();
Your loop condition is currently your random number, that's why it will run until the number is 10 by chance. You need to initialize a separate counter variable which gets incremented in each iteration of your loop.
Also your current calculation Math.floor(Math.random() * 10) + 1 would only return numbers from 1 to 10 (excluding 0).
And read about the setInterval function. I'm not sure if that's what you actually want to achieve.
I think you never change i in loop.
this works:
function testNumber () {
let i=(Math.floor(Math.random() * 10)+1)
const interval=
setInterval( () => {
i=(Math.floor(Math.random() * 10)+1)
document.write("Random number: " +i.toString())
if(i==10) clearInterval(interval)},1000)
}
function test () {
testNumber()
}
test()
clearInterval(interval) allows you to exit interval.

Checking setInterval every 5 minutes on the 0 second

const secondsInterval = () => {
const date = getNow();
if (dayjs(date).minute() % 5 !== 0 && dayjs(date).second() !== 0) {
console.log("return...");
return;
}
console.log("checking...");
...
};
// Check every second, if we're at the 5-minute interval check.
setInterval(secondsInterval, 1000);
This seems to get stuck. It's "checking" on every second of each 5 minute mark. What am I doing wrong? Thanks in advance.
Goal: To "check" every minute and 00 seconds: :00:00, :05:00, :10:00, , :15:00, etc Thanks again.
You should find out what's the time to your next rounded 5 min. like this:
const FIVE_MIN = 1000 * 60 * 5;
function waitAndDoSomething() {
const msToNextRounded5Min = FIVE_MIN - (Date.now() % FIVE_MIN);
console.log(`Waiting ${msToNextRounded5Min}ms. to next rounded 5Min.`);
setTimeout(() => {
console.log('It is now rounded 5 min');
waitAndDoSomething();
}, msToNextRounded5Min);
}
waitAndDoSomething();
If all you care about is executing some code every 5 mins, then don't have it execute every second needlessly, only to return out. Just have it run every 5 mins (300000 MS) and have it do what you need to do and remove all the checking for 5 minute mark code out its unnecessary.
const secondsInterval = () => {
// -------------------- Remove ----------------
//const date = getNow();
//if (dayjs(date).minute() % 5 !== 0 && dayjs(date).second() !== 0) {
// console.log("return...");
// return;
//}
// -------------------- Remove ----------------
console.log("checking...");
...
};
// Check every 5 mins
setInterval(secondsInterval, 300000);
Your logic for the if is screwy. Here I reversed it so the if takes care of "do the thing" and the else returns.
const secondsInterval = () => {
const date = dayjs(new Date());
if (dayjs(date).minute() % 5 == 0 && dayjs(date).second() == 0) {
console.log("checking...");
} else {
console.log("returning...");
return;
}
//...
};
// Check every second, if we're at the 5-minute interval check.
setInterval(secondsInterval, 1000);
<script src="https://unpkg.com/dayjs#1.8.21/dayjs.min.js"></script>

How do I modify this code to create a loop inside a loop?

I found this script from a website. The loop ends when it has followed 40 Instagram accounts at a 2-second interval. How do I modify the script so it waits for 10 minutes before repeating the same loop for 3 times? Basically, it goes:
Follow an account and wait for 2 seconds X40
Wait for 10 minutes
Follow an account and wait for 2 seconds X40
Wait for 10 minutes
Follow an account and wait for two seconds X40
Wait for 10 minutes
---LOOP ENDS---
var TagFollow = document.getElementsByTagName("button");
var SearchFollow = "Follow";
var foundFollow;
function clickfollow(){
for (var i = 0; i < TagFollow.length; i++) {
if (TagFollow[i].textContent == SearchFollow) {
foundFollow = TagFollow[i];
foundFollow.click();
break;
}
}
}
var i = 1;
function myLoop() {
setTimeout(function() {
console.log(new Date().toLocaleTimeString());
clickfollow();
//document.getElementsByTagName("ul")[3].scrollIntoView(false
i++;
if (i < 41) {
myLoop();
}
}, 2000)
}
myLoop();
Thanks in advance!
You do not need nested loops. You can "linearize" them in single loop (I do not recall the correct therm now). So basically you want loop of 3 * 40 = 120 and after each 40 you need to use increased delay of 10 * 60 * 1000 = 600000. You help yourself by using modulo function i%40. Because you start with 1, the each 40th iteration is when remainder of i divided with 40 is zero.
So basically change if (i < 41) to if (i < 121) and }, 2000) to }, i%40 === 0 ? 600000 : 2000)

Is there a way to iterate through a timer in React?

I'm trying to create a Pomodoro timer using Hooks and I have set up the basic functionality using useState and useEffect. I have a 25-minute timer that counts down and every time it gets to 0, it starts a break timer of 5 minutes. What I'm trying to figure out now is how to create an iteration that says "every 4 times the timer hits 0, change the break time from 5 minutes to 15 minutes and then, go back to 5 minutes." I thought of creating sessions that way it will say 4th session and then it will go back to 1. but I'm really not sure what to do here.
import React, { useState, useEffect } from "react";
function Pomodoro() {
const [minutes, setMinutes] = useState(25);
const [seconds, setSeconds] = useState(0);
const [displayMessage, setDisplayMessage] = useState(false);
const [session, setSession] = useState(1);
useEffect(() => {
let interval = setInterval(() => {
clearInterval(interval);
if (seconds === 0 && minutes !== 0) {
setSeconds(59);
setMinutes(minutes -1);
} else if (seconds === 0 && minutes === 0) {
let minutes = displayMessage ? 24 : 4;
let seconds = 59;
setSeconds(seconds);
setMinutes(minutes);
setDisplayMessage(!displayMessage);
} else {
setSeconds(seconds -1);
}
}, 1000);
}, [seconds]);
const timerMinutes = minutes < 10 ? `0${minutes}` : minutes;
const timerSeconds = seconds < 10 ? `0${seconds}` : seconds;
return (
<div className="pomodoro">
<div>Session:{session} </div>
<div className="message">
{displayMessage && <div>Break time! New Session starts in:</div>}
</div>
<div className="timer">
{timerMinutes}:{timerSeconds}
</div>
</div>
);
}
export default Pomodoro;
Your approach using a counter to keep track of the completed sessions seems to make sense. If you want to use a different amount of break time for every fourth iteration, you could use the remainder operator as below:
let breakTime = (session % 4) === 0 ? 14 : 0;
Then, you just need to make sure you are incrementing your session variable by one each time you complete a session. This also means you only want to increase it when you are not "on break" so you must make sure to guard against that.
Updating the answer with the full code that I tested to be working. Note the following changes I made:
I am only keeping track of the timer in seconds - this reduces the complexity inside useEffect and you can convert from seconds to other formats (try using the remainder operator again)
Moved the period lengths to constants
Renamed the variable displayMessage to isOnBreak for clarity
import React, { useState, useEffect } from "react";
// Define the period lengths (in seconds)
const workTime = 2;
const shortBreakTime = 4;
const longBreakTime = 6;
function Pomodoro() {
const [seconds, setSeconds] = useState(workTime);
// Renamed this variable for clarity to indicate it is a boolean
const [isOnBreak, setIsOnBreak] = useState(false);
const [session, setSession] = useState(1);
useEffect(() => {
let interval = setInterval(() => {
clearInterval(interval);
if (seconds === 0) {
let breakTime = (session % 4 === 0) ? longBreakTime : shortBreakTime;
let seconds = !isOnBreak ? breakTime : workTime;
// A session is complete when work and break is done,
// so only increment when finishing a break
if (isOnBreak) setSession(session+1);
setSeconds(seconds);
setIsOnBreak(!isOnBreak);
} else {
setSeconds(seconds -1);
}
}, 1000);
}, [seconds]);
// Here you could convert from seconds to minutes and seconds or whatever time format you prefer
const timerSeconds = seconds < 10 ? `0${seconds}` : seconds;
return (
<div className="pomodoro">
<div>Session:{session} </div>
<div className="message">
{isOnBreak && <div>Break time! New Session starts in:</div>}
</div>
<div className="timer">
{timerSeconds}
</div>
</div>
);
}

Summing a number recursively and displaying it [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I searched for a solution to this problem quite a bit, but couldn't reach a solution. Would be great if someone can point me in the right direction.
Ok, so suppose there's a number :-
0.001
What I want to do is, add 0.001 (the same number) to it again and again ever second and also display the change dynamically.
So :-
second 1 :- 0.001
second 2:- 0.002
second 3 :- 0.003
This has to keep running for 1 hour and I should be able to see it's value changing dynamically on my web page. How can I achieve this? I did quite a research on using countup.js, but no result. I thought of a solution to use ajax, but this would cause a lot of load.
Whats the best that I can do here?
You can also try this
<div id="display"></div>
var number = 1;
var timer = function(){
number++;
document.getElementById('display').innerHTML = parseFloat(number / 1000);
if(number < 3600){ // 1 hour check
setTimeout(timer,1000);
}
};
timer();
simple with js
var value = 0.001; //value to start
var inc = 0.001; //increment
var end = 0.010; //to test , 1 hour is 3.600
var _interval = setInterval(function() {
document.getElementById('midiv').innerHTML = value;
value += inc;
value = parseFloat(value.toFixed(3));
if (value > end) {
clearInterval(_interval);
}
}, 1000);
<div id="midiv">
</div>
Here is an example using rxjs
var interval = 1000;
var totrun = 60*1000
var v = 0
const source = Rx.Observable
.interval(interval)
.takeUntil(Rx.Observable.timer(totrun));
const subscription = source.subscribe(
t => {
v=v+0.001
$('#v').html(v);
},
err => console.log('Error: ' + err),
() => console.log('Completed'));
Is this what you want?
feel free to play with it
var c = 0.000;
var count = document.getElementById('count');
count.innerHTML = c;
// Creates the interval with the name interval
var interval = setInterval(function() {
c += 0.001
count.innerHTML = c;
// Its possible that you will see 0.00300000000007 artifacts
// You can fix it by converting it to a string and showing only a part
// count.innerHTML = ("" + c).substring(0, 5);
}, 100) // 1/10 sec for demo
// Clear the interval after one hour
setTimeout(function() {
clearInterval(interval)
}, 1000) // one second for demo
counter: <span id="count"></span>
var interval = setInterval(function(){
var old = parseFloat($(".number").html());
var newValue = old + 0.001;
$(".number").html(newValue);
}, 1000);
// this clears the interval loop from firing after 1 hour
setTimeout(function(){
clearInterval(interval);
}, 3600000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="number">0.001</div>
That should do the trick

Categories