Can someone please help me out with this? I'm getting an error 'count is not defined' when executing the below code. I'm trying to create a countdown clock in node.js. If I log the timer variable inside the function it works but outside of the function, it is undefined.
const getOrder = async(request, response) => {
const data = await knex("orderbook_table").select()
const time_data = await knex("orderbook_table").select("timestamp")
console.log(time_data)
var timer;
setInterval(function count() {
for (var i = 0; i < time_data.length; i++) {
//console.log(tableRows[i]);
var entryDate = time_data[i].timestamp;
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
countDown = new Date(entryDate).getTime();
let now = new Date().getTime();
distance = countDown - now;
days = Math.floor(distance / (day));
hours = Math.floor((distance % (day)) / (hour));
minutes = Math.floor((distance % (hour)) / (minute));
seconds = Math.floor((distance % (minute)) / second);
timer = days + "d:" + hours + "h:" + minutes + "m:" + seconds + "s";
//console.log(timer);
}
}, 1000);
var orderStr = data;
count();
console.log(timer);
response.send({ orderStr });
//refresh()
The count function is defined and scoped under the setTimer, you should create the function as callback outside of setInterval then call within that setInterval the created function
You can give a look to this previously answered thread or to the documentation
Related
I made a 5 minute(300 seconds) cooldown for my discord.js bot, but when someone uses it more than once in under 5 minutes, it sends something like:
#Edward, please wait 250.32 second(s) until you can use this command!
Is there any way to change 250.32 seconds to something like 4 minutes 10 seconds or something close to that? I'm a noob at Node.js so help would be greatly appreciated.
if (!cooldowns.has(command)) {
cooldowns.set(command, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command);
const cooldownAmount = 1 * 300 * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`Please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
Read this discussion.
Basically you need to divide seconds with 60 to get minutes and then you use % to get the reminder:
const cooldownAmount = 1 * 275.45 * 1000;
const timeLeft = cooldownAmount / 1000;
var quotient = Math.floor(timeLeft / 60); //minutes
var remainder = Math.floor(timeLeft % 60); //seconds
console.log(quotient); // 4
console.log(remainder); // 35
This code should work in your case:
if (!cooldowns.has(command)) {
cooldowns.set(command, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command);
const cooldownAmount = 1 * 300 * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
var quotient = Math.floor(timeLeft / 60); //minutes
var remainder = Math.floor(timeLeft % 60); //seconds
return message.reply(`Please wait ${quotient} minutes and ${remainder} seconds before reusing the \`${command}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
I have started a game and I want a stopwatch (countup timer) in it I have found a code to activate it. But how to stop it?
Source: https://docs.idew.org/video-game/project-references/phaser-coding/timers#create-count-up-timer
Code related to the stopwatch:
//global vars
var timeText; var min, sec;
function create timeText = game.add.text(600, 20, "", { fontSize: '20px', fill: '#FFF' }); timeText.fixedToCamera = true;
function displayTimeElapsed(){
if (knight.x >= 96){
var time = Math.floor(game.time.totalElapsedSeconds() );
min = Math.floor(time / 60);
sec = time % 60;
if (min < 10) {
min = "0" + min;
}
if (sec < 10) {
sec = "0" + sec;
}
timeText.text = "Time: " + min + ":" + sec;
}
}
//update displayTimeElapsed();
you could add a boolean pause that if true it will set the time to what the remaining time is and when false keep doing what is doing.
it would be easier to explain it if you show your code. I will update my answer accordingly.
Lets create it from scratch,
first of all in your create() function, lets add a text to display the timer on the screen:
// CREATE()
this.timerText = this.add.text(x, y, "").setColor("#000000");
Second lets create a function, bellow the update(), to count down :
showTimer(){
// Assuming you want 60 seconds, if not just chenge the 60's for whatever time you want
let maxTime = 60;
let time = Math.floor(this.time.totalElapsedSeconds() );
let sec = time % 60;
timeText.setText(sec); // Adding the timer to our text
}
Third, create a variable in the create() to track when the timer ends:
// CREATE()
this.timerOver = false;
// And lets start the timer
this.timer = this.time.delayedCall(60000);
Now lets modify our showTimer() function:
showTimer(){
let maxTime = 60;
let time = Math.floor(this.time.totalElapsedSeconds() );
let timeLeft = maxTime - time; // Check how much time is left
// When the countdown is over
if(timeLeft <= 0){
timeLeft = 0;
this.timerOver = true; // Setting our variable to true
}
let sec = time % 60;
timeText.setText(sec);
}
and last, in our update() function lets check if our variable this.timerOver is true
if (this.timerOver === false){
this.showTimer(); // Calling our function every frame
}
else {
// Whatever you want it to do when timer comes to 0
}
I am trying to print dates by adding more days to them by using nlapiAddDays() in a loop
var startdate = nlapiGetLineItemValue('item','custcol_startdt',i+1);
var enddate = nlapiGetLineItemValue('item','custcol_enddt',i+1);
var stringtodate1 = nlapiStringToDate(startdate);
var stringtodate2 = nlapiStringToDate(enddate);
//BELOW FORMULA I USED TO GET NUMBER OF MONTHS BETWEEN TWO DATES
var diff =(stringtodate2.getTime() - stringtodate1.getTime()) / 1000;
var diffMonths = Math.ceil(diff / (60 * 60 * 24 * 7 * 4)-1);
if(diffMonths > 1)
{
for(i=0; i <= diffMonths; i++)
{ var AddDays = 30;
var days = null;
if(i == 0)
{
days = stringtodate1;
}
else
{
days = nlapiAddDays(stringtodate1, AddDays);
}
}
nlapiLogExecution('DEBUG','days',days);
AddDays++;
}
here,if i becomes 1,30 days are added but when i becomes 2, 60 days should get added because of AddDays++ but it is not happening.30 days are added for every loop.
You are resetting AddDays to 30 at the top of the loop. You would need:
var AddDays = 30;
for(i=0; i <= diffMonths; i++)
{ ...
I have been developing in PHP for many years and now I´m trying to learn NodeJS, and I´m having problems with asynchronous functions...
I have this function in NodeJS (source is an array of users):
//userformat.js
var age = module.exports.age = function(date){
var diff = new Date - new Date(date);
var diffdays = diff / 1000 / (60 * 60 * 24);
var age = Math.floor(diffdays / 365.25);
return age;
}
...etc.
//index.js
function format(source, me, callback){
var len = source.length
for (var i = 0; i < len; i++){
source[i]['_age'] = userFormat.age(source[i]['birthday']);
source[i]['_rating'] = userFormat.rating(source[i]['votes']);
source[i]['_is_followed'] = userFormat.followed(source[i]['fllws'], me);
}
callback(null, source);
}
I know that function is wrong in Node, because is possible that the function calls the callback before the functions in the for() had finished, and the values in the array could be undefined, for this reason I changed the function using callbacks:
//userformat.js
var age = module.exports.age = function(date, callback){
var diff = new Date - new Date(date);
var diffdays = diff / 1000 / (60 * 60 * 24);
var age = Math.floor(diffdays / 365.25);
callback(age);
}
...etc.
//index.js
function format(source, me, callback){
var len = source.length
for (var i = 0; i < len; i++){
userFormat.age(source[i]['birthday'], function(resul){
source[i]['_age'] = resul;
userFormat.rating(source[i]['votes'], function(resul){
source[i]['_rating'] = resul;
userFormat.followed(source[i]['fllws'], me, function(resul){
source[i]['_is_followed'] = resul;
//Callback
if (i == len-1){
callback(null, source);
}
})
})
})
}
}
That is correct? I have another way to do it more efficient or elegant?
Thank you so much!
I think you misunderstood the concept of asynchronous in nodeJS. Your code isn't asynchronous and your callback will always be called after the loop.
Check this question : how do i create a non-blocking asynchronous function in node.js?
How can I create a count down timer in JSF? I don't want the timer reset when refresh the page.
You can simply use Java Script for it.
Or
You can use RichFaces a4j:poll and poll count data from server where your timer will be running
You can use simply this script
var seconds = readCookie('countdown') || 60;
alert(seconds);
function secondPassed()
{
seconds--;
var minutes = parseInt(seconds / 60);
var remainingSeconds = parseInt(seconds % 60);
if (remainingSeconds < 10) {
remainingSeconds = "0" + parseInt(remainingSeconds);
}
document.getElementById('countdown').innerHTML = minutes + " mins : " + remainingSeconds + " secs";
if (parseInt(seconds) === 0)
{
alert("Time is over");
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Time is Over";
document.forms["myForm"].submit();
document.location.href = "examresult.jsp";
}
}
var countdownTimer = setInterval(function() {
secondPassed();
if (seconds === 0) {
eraseCookie(seconds);
} else {
createCookie(seconds, seconds, 7);
}
}, 1000);