I'm making a function to clear my local storage every month and set a 25 hour cooldown timeout so it wont activated again after executed but always got reset and keep executed everytime.
Please help to fix this. Thanks
let cooldown = false;
const RECHARGE_TIME = 90000000; //25 hour cooldown
let today = new Date()
document.getElementById("todayDate").innerHTML = today.getDate();
if(today.getDate() === 1 && !cooldown){
clearHighScore();
startCooldown();
}
console.log(cooldown) //just to check the cooldown state
function clearHighScore() {
localStorage.clear();
}
function startCooldown() {
cooldown = true;
setTimeout (function(clearHighScore){ cooldown = false}, RECHARGE_TIME);
}
Related
I've been working on this command (that I have a problem with) where when the user says u?hi, the bot replies before putting you in a set. You are then put in a timeout for 20 seconds, and while you are in the timeout, if you type u?hi, the bot replies gotta wait x seconds. When the timeout ends, they can type u?hi and the cycle keeps going.
However, I've encountered a problem. In my code, after doing u?hi, I get put in a timeout (just like how I planned). However, while in the timeout, if I type u?hi while lets say 1 seconds into the timeout, instead of the bot saying gotta wait 19 more seconds, the bot says gotta wait 19 more seconds and then starts counting down all the way to 0. Here's what I mean (Screenshot):
Here's my code:
const intervalSet = new Set();
bot.on("message", msg => {
let args = msg.content.substring(prefix.length).split(" ");
switch (args[0]) {
case "hi":
var interval = 20;
var intervalID;
if (intervalSet.has(msg.author.id)) {
intervalID = setInterval(() => {
interval -= 1;
if (interval !== 0 && args[0] === 'hi') {
msg.channel.send(`gotta wait ${interval} more seconds`);
}
if (interval === 0) {
clearInterval(intervalID);
msg.channel.send(`Ended`);
intervalSet.delete(msg.author.id);
}
}, 1000);
} else {
intervalSet.add(msg.author.id);
msg.channel.send("heyy");
}
}
});
I've tried moving the
if (interval !== 0 && args[0] === 'hi') {
msg.channel.send(`gotta wait ${interval} more seconds`);
}
part to other places of the code and changing it up but nothing seems to work. What can I do about this?
Yes that's normal with your code. What you need to do is to create a map, named cooldown. User IDs will be linked with times, so you'll be able to calculate for how long the user is in cooldown.
Here is an update of your code:
const cooldown = new Map();
bot.on("message", msg => {
let args = msg.content.substring(prefix.length).split(" ");
switch (args[0]) {
case "hi":
var interval = 20000; // use milliseconds instead of seconds
var intervalID;
if (cooldown.has(msg.author.id)) {
let cooldownTime = Date.now() - cooldown.get(msg.author.id);
let timeToWait = (interval-cooldownTime)/1000;
if(cooldownTime < interval) {
return message.channel.send(`gotta wait ${timeToWait} more seconds`);
}
}
cooldown.set(msg.author.id, Date.now());
msg.channel.send("heyy");
}
});
If you have any questions, don't hesitate to post a comment!
I want to build a "timer". User can define a duration and the interval. So it will start with a warnsignat, then there will be a warnsignal, which peeps every interval and at the end there should be one.
The problem is: it doesn't work.
The audio just plays all the time.
Possible errorsources:
peep.loop = false does not work
it does not block.
const peepUrl = require('./../../../Assets/peep.mp3');
const peep = new Audio(peepUrl);
peep.loop = false;
_peep = () => {
peep.play();
if(this.state.myInterval > 0) {
setTimeout(() => {
peep.play();
}, 60000*this.state.myInterval);
}
clearInterval(this.state.myDuration)
peep.play();
}
I am trying to store information with the webstorage API. I created a class but the console returns the message "undefined". I was expecting the console to return 20 and 60. Can you help me identify my mistake? Thank you :)
class Timer {
constructor(minutes, secondes){
this.minutes = minutes;
this.secondes = secondes;
this.minutesEltHtml = document.getElementById("minutes");
this.secondesEltHtml = document.getElementById("secondes");
}
setMinutesSecondes(){
sessionStorage.setItem("minutes", this.minutes);
sessionStorage.setItem("secondes", this.secondes);
}
getMinutesSecondes(){
return sessionStorage.getItem("minutes");
return sessionStorage.getItem("secondes");
}
display(){
console.log(timer.getMinutesSecondes());
//console.log(timer.this.minutes);
}
}
let timer = new Timer(20, 60);
timer.display();
Line 20: undefined
1: You don't set the storage as you are not calling the method that does it. either call timer.setMinutesSecondes() before calling display or do so in the constructor as per my example below.
2: It's seconds not secondes (sorry for the pedantry).
3: Your getMinutesSecondes function has 2 return calls. Execution will stop after the first call. see my example below.
4: Some of the mistakes here indicate you would benefit from some introduction to JavaScript courses. Have a quick google, there is a wealth of free content online.
class Timer {
constructor(minutes, secondes){
this.minutes = minutes;
this.secondes = secondes;
this.minutesEltHtml = document.getElementById("minutes");
this.secondesEltHtml = document.getElementById("secondes");
this.setMinutesSecondes();
}
setMinutesSecondes(){
sessionStorage.setItem("minutes", this.minutes);
sessionStorage.setItem("secondes", this.secondes);
}
getMinutesSecondes(){
return { // you were calling return twice... only the first line would have returned
mintues: sessionStorage.getItem("minutes"),
secondes: sessionStorage.getItem("secondes")
};
}
display(){
console.log(this.getMinutesSecondes());
}
}
let timer = new Timer(20, 60);
timer.display(); // output {minutes:20, secondes:60}
The reason you are getting undefined as the return value of sessionStorage.getItem is because the value you are trying to retrieve from the storage has not be set on that storage. You defined a method to store the data to the storage without calling that method ( setMinutesSecondes ).
Do this instead ( Assuming the code you presented is your complete code )
class Timer {
constructor(minutes, secondes){
this.minutes = minutes;
this.secondes = secondes;
this.minutesEltHtml = document.getElementById("minutes");
this.secondesEltHtml = document.getElementById("secondes");
}
setMinutesSecondes(){
sessionStorage.setItem("minutes", this.minutes);
sessionStorage.setItem("secondes", this.secondes);
}
getMinutesSecondes(){
return {
minutes: sessionStorage.getItem("minutes"),
secondes: sessionStorage.getItem("secondes");
};
}
display(){
console.log(timer.getMinutesSecondes());
//console.log(timer.this.minutes);
}
}
let timer = new Timer(20, 60);
timer.setMinutesSecondes(); // if you don't wish to call this method here, you can still call this method in the constructor function
timer.display();
Right now I have this in my componentDidMount() methode:
setInterval(() => this.getTimeUntil(getTheTimeToAdd, count++), 1000);
It calls another methode for updating every second to count down. I have a problem when the user is counting down the application might close or the iPhone goes to sleep.
I have tried to use both:
react-native-mauron85-background-geolocation
and:
react-native-background-timer
To keep the count down running even when the iPhone sleeps og the application is closed. Any suggestions?
What you can do is create new Dates for each invocation to see the elapsed time. Like
setInterval(function() {
Date d = new Date();
if (this.oldDate && this.oldDate.getTime() + DELAY_THRESHHOLD < d.getTime()) {
...
this.oldDate = d;
}
else {
... //should anything be here?
}
},500);
Since you're already using react-native-background-timer,
you can use the setInterval from the BackgroundTimer instance.
Assuming that you've linked the project correctly, you should be able to do
// In the constructor or the state
this.state = {
initialCounter: 120000, //Equivalents to 2 minutes
active: false, // To show or hide a label
}
componentWillMount() {
this.setIntervalId = BackgroundTimer.setInterval(() => {
if (this.state.initialCounter === 0) {
this.setState({
initialCounter: this.state.initialCounter,
active: true,
})
} else {
this.setState({
initialCounter: this.state.initialCounter - 1000,
active: false,
})
}
}, 1000)
}
// Make sure to unmount the listener when component unmounts
componentWillUnmount() {
BackgroundTimer.clearInterval(this.setIntervalId)
}
// Helper func to reinitiate the counter
_onUpdate = () => {
this.setState({ initialCounter: 120000, active: false })
}
// And inside your render you may display the timer by formatting with moment()
The docs are a bit misleading, since setInterval and clearInterval works on IOS too. Tested on package 2.0.1
Try this code, it should catch up every time the app wakes up.
const duration = 15; // duration in minute
const alertAt = Date.now() + duration * 60 * 1000;
const interval = setInterval(() => {
const remaining = alertAt - Date.now();
if (remaining < 0) {
// time is up
clearInterval(interval);
return;
}
console.log(remaining);
}, 10)
I've a page with a chart on it, the chart is update via JS using a setinterval of 20 seconds, now my session is not expiring, i've searched over the internet and didn't found something like this, how i would detect user inactivity with this chart running?
setInterval(function(){
$.ajax({
type:'POST',
url: 'php/grafico.php',
success: function(e){
e = JSON.parse(e);
var linhas = e['linhas'];
var label = new Array();
for(var i = 1;i <= linhas; i++){
label.push('');
}
var preco = new Array();
for(var i = 1;i <= linhas; i++){
preco.push(e[i]['preco']);
}
addData(chartGraph, preco, 0, label);
}
});
var base = $('#Layer_base').height();
$('#menuzinhu').css('min-height',base+'px');
}, 20000);
heres the setinterval function, how it will update the session so it will never expire, but i need it to expire.
Thanks in adv.
You could create a timeout, which is set to fire, the value of the time being how long you should wait for user input/events before deeming them inactive. You'd then reset the timeout whenever an event is triggered by the user, where you define what events signify user activity.
See below for an example, this is untested, but should see you on the right track.
var inactiveTime = 30000; //30 seconds
var interactionEvents = [
"onload",
"onmousemove",
"onmousedown",
"ontouchstart",
"onclick",
"onscroll",
"onkeypress"
];
var timeoutId = null;
var finished = function () {
//You'd put your logic in here to clear the session.
//This gets fired when the user is deemed inactive.
console.log("User inactive.");
};
//Keep track of if the timer has finished, handy if the user stays on
//the page when this has finished, as you can compare it's value to
//detirmine if you should keep running the timeout.
var hasFinished = false;
var reset = function () {
if (hasFinished === true) {
return;
}
//Clear any already running timeout
clearTimeout(timeoutId);
//Start the new timeout
timeoutId = setTimeout(function () {
hasFinished = true;
if (typeof(finished) === "function") {
finished();
}
}, inactiveTime);
//If events reset the timer, apply them
//Attach events which will reset the timer
for (var i = 0, max = interactionEvents.length; i < max; i++) {
document[interactionEvents[i]] = reset();
}
};
//Start the timer with this
reset();
Something like that!