I'm sure this has been asked before but I can't seem to find anything that helps, I hope the title make sense, I'm new to javascript and node. In short, I am creating bot for an internal messaging system (like slack). My bot is a reminder bot, so a user can type in the keyword and say "remind me of 'x' in 10 minutes" or "remind me to do 'y' on April 30th at 9:00am" etc.
In my head it made sense to just a have global time variable that is constantly updated like:
if(currentDateTime >= reminderArray[0].notificationTime){
bot.sendMessage(reminderArray[0].message);
reminderArray.shift();
}
push all the reminders on a global queue where they are sorted by reminder time and then execute the bot to send a message when the global time equals the time of the first item in the queue.
I am having a really hard time figuring out how to have a live updated global time variable. I have looked into cron jobs but I'm not sure how to have multiple cron jobs running at the same time.
I have no idea if I'm thinking about it too much or not, it's been like 3 days of banging my head on my keyboard so I might just be in a hole and the answer is probably really simple. Anyways if you can shed any light, offer any advice, or show any examples/tool that I can use I would be so thankful.
Wait, as I was rephrasing the question I realized that code block could work if I put it inside a setInterval(). Something like this:
setInterval(() => {
const time = moment();
if(time >= reminderArray[0].notificationTime){
bot.sendMessage(reminderArray[0].message);
reminderArray.shift();
}
},6000)
what about setTimeout function? You can wrap in setTimeout your function, and your function will be called after N milliseconds, first argument function, second, time in milliseconds, for example:
setTimeout(() => {
console.log('I remind you');
}, 1000)
For your first case, remind me in x minutes, you can use previous, for the second case: remind me to do 'y' on April 30th at 9:00am", you can use something like that:
const reminder = (time) => //argument time in milliseconds which user set
const now = Date.now();
setTimeout(() => {
console.log('I remind you');
}, now + time - now)
For more information about Date.now and setTimeout visit: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Date/now
https://developer.mozilla.org/ru/docs/Web/API/WindowTimers/setTimeout
Hope I could help you!
Related
I came across this simple(or what I thought so) question on a Javascript MCQ Test:
After how much time will the following code execute entirely?
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
Options
A) 1 second
B) 2 seconds
C) 4 seconds
D) 5 seconds
I answered as option D) 5 seconds since EACH line above will take 1000 milliseconds to execute i.e a total of 5000 milliseconds = 5 seconds
But in the results, it said that the actual answer is Option A) 1 second.
I executed those five lines in my console (altogether) and the entire code executed after 1 second like the answer said.
I don't understand the logic behind the right answer, and why my reasoning was wrong.
because setTimeout works asynchronously, means all of these 5 statements will be executed simultaneously and all of these will start waiting for 1 second. and after one second all will be executed. hope it clears.
Each call you make it running in it's own background thread (it's own unique operation), when you call setTimeout, you're telling JavaScript that you want to execute your code after 1 second has passed.
If you wanted to make this last 5 seconds you would do something along the lines of:
setTimeout(function() {
console.log("First task")
setTimeout(function() {
console.log("Second task");
},1000);
},1000);
This would execute the first task, once called it will execute the second task
Edit: I saw another post about doing it non-async, you want to avoid doing anything non-async in JavaScript as it will hold up the browser which is general is a bad practice and bad user experience
From the MDN page:
The setTimeout() method ... sets a timer which executes a
function or specified piece of code once the timer expires.
So I am creating an event to listen when there is a message and tell the time from when the last message that was sent. But I can't seem to figure out how to do just that. (I used message.author.lastMessage.createdTimestamp - new Date().getTime()) This does not seem to create a consistent time when I test it out. Any help on what's wrong or anything I need to fix would be appreciated
I recommend you to keep it simple and only use Dates.
// takes a User and returns the milliseconds of difference between now
// and the last message, if there's one.
function lastDiff({ lastMessage }) {
if (lastMessage) return new Date() - lastMessage.createdAt;
}
lastDiff(message.author);
Keep in mind that this can't always print the same number since milliseconds can change between a check and the next one.
Once you have the milliseconds, you can format them as you want.
I want to write a javascript function that takes very close to 5 seconds to run. How can I make that guarantee?
I have tried
function wait(numSeconds) {
var end = new Date().getMilliseconds() + numSeconds * 1000;
while (new Date().getMilliseconds() <= end) {}
}
but this just crashes the page.
You cannot freeze the page without freezing the page.
You're trying to write a function that runs for 5 seconds straight.
Javascript runs on the UI thread, so the page will be frozen whenever any code runs.
In short, you can't do that.
You need to write asynchronous code, probably by using setTimeout().
you can use:
var t = setTimeout(function(){alert('done')},5000);
If you want to wait 5 seconds before doing something, use setTimeout or setInterval. Otherwise, just eating up user time is a bad idea. In fact, the browsers will interrupt your script if it takes too long to do something, which your function most certainly will do.
(Ignoring for the moment why you shouldn't really do this...)
The reason your code is freezing the browser is that your while condition will never become true (for numSeconds of 1 or more).
The .getMilliseconds() method returns just the milliseconds part of the date, i.e., a number between 0 and 999. For numSeconds of 1 of more your end will always be greater than 999.
Try using .getTime() instead of .getMilliseconds(). Or if you don't care about supporting old browsers uses Date.now().
You could just use javascripts setTimeout instead of your own wait function.
setTimeout excecutes a function after a certain amount of time.
For example:
setTimeout(function(){}, 5000);
Would just wait 5 seconds.
See more at w3schools.
Strictly speaking, what you ask cannot be done because, as you've seen, the page will freeze while you wait.
As a practical matter, though, I suspect that what you really want is the something like this:
function waitawhile() {
setTimeout( function() {
alert('5 seconds has passed');
}, 5000);
}
I am having trouble dynamically seeing the time update with moment js. It shows the correct time but I have to refresh my browser to get the time update. I would like it to update it in real time. Like momentjs.com main page.
I've tried using setInterval and setTimeout but for some reason I get the below digits that don't even update.
Here's what I have so far code-wise. Pretty simple as far as moment goes and all I want is seconds to keep counting...
update = ->
time = moment().format('hh:mm:ss a')
clock = setInterval update, 1000
console.log(clock) //output: 53296
Any ideas are immensely appreciated.
You should put the output inside of the update method and everthing will work as expected.
The method setInterval won't return the result of the repeatedly called method but an identifier which can be used with clearInterval to stop the execution.
Just a small working example to print the time every seconds and stop after 10 seconds:
update = ->
console.log(moment().format('hh:mm:ss a'))
x = setInterval update, 1000;
setTimeout (-> clearInterval(x)), 10000
If you want to use that time as content of some DOM-Element you can use the following code inside your update function (assuming you have an element (e.g. div) with id "time"):
JQuery:
$("#time").text(moment().format('hh:mm:ss a'))
Plain JS:
document.getElementById("time").firstChild.data = moment().format('hh:mm:ss a')
Try this. If u are dont have to use meomentJS.
https://github.com/furkankaynak/countdown
I'm having a hard time understanding the logic behind the setTimer method in javascript.
<html><head>
<script>
function Timer () {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
document.getElementById('show').innerHTML=h+":"+m+":"+s;
t = setTimeout("Timer()", 1000);
}
</script>
</head>
<body onload="Timer()">
<div id="show"></div>
</body></html>
setTimeout is used to delay a function/method execution. Then why it is being used in a real-time clock?
t = setTimeout("Timer()", 1000);
This part is confusing.
The clock is recursively calling itself, after the elapsed period of time.
Making a real-time clock is impossible in JS.
Because of how JS engines work, if you put Timer in a loop, to run for an infinite period of time, you'd never see the time update on the screen (as changes aren't drawn to the window until a function finishes and there's a gap in the program).
Also, inside that infinite-loop, it would be impossible to do anything else with the page (even closing it), because JS can only do one thing at a time, so it can't listen to any of the user's clicking until it's done with this loop.......
So that's what the setTimeout is for.
Timer is the function which acts as the clock.
Inside of the Timer function, at the end when all of the work is done, it's telling setTimeout to wait 1 second (1000ms) and then to call a function called Timer.
Timer just so happens to be the same function. But setTimeout doesn't know that, and doesn't care.
The t in this case is largely useless. setTimeout will return a number -- like taking a number at the doctor's office.
If, before you go through with it, you decide to back out, you can call clearTimeout(t); and it'll skip over that call (in this case, it would stop calling the clock).
There are a few bad-practices in here, that I figure I should mention, so that you can try not to copy them in your own practice.
First:
Pass setTimeout a reference to a function, and not a string...
var runThisFunction = function () { console.log("It's the future!"); },
time_to_wait = 250;
// DON'T DO THIS
setTimeout( "runThisFunction()", 250 );
// DO THIS
setTimeout( runThisFunction, 250 );
The difference is that setTimeout will run that string through eval, which can be a huge security concern depending on what you're trying to do.
The second problem is setting a random global variable, t... ...and hoping to use that as a solution.
First, in a couple of years, JS engines are going to start yelling at people for doing that stuff. Second, it's a huge hole, because any part of any app on that page could then overwrite t, or you could be relying on t somewhere else in your script, but every 1000ms, it gets written over with a new number.
Instead, they probably should have used a Timer.start(); and Timer.stop(); setup.
Your code:
t = setTimeout("Timer()", 1000);
The first thing you should know is that it's considered bad practice to put the first parameter in a string -- it should be the function name, unquoted, and without brackets, like so:
t = setTimeout(Timer, 1000);
That aside, your question about why it's being used to display a clock:
The use of setTimeout() inside the Timer() function to call itself is a common Javascript pattern to get a function to be called repeatedly. setTimeout() itself only triggers the function to be called a single time, after the given period of time has elapsed, so for a repeating event it needs to be re-triggered every time.
Since the setTimeout call is inside the Timer() function, it won't be set until Timer() is called the first time by some other means. This is where the body onload comes in.
As you suspect, setTimeout() isn't an accurate method for guaranteeing that a function will be called after exactly a given amount of time. Javascript is not multi-threaded, so any event handlers that are triggered must wait for any other code that is running at the same time. If something else is running slowly, this may cause your timer not to be triggered at exactly the moment it wants to be.
However, this isn't really a problem for your clock , because the clock is setting itself to the actual system time rather than relying on the setTimeout loop to keep itself in sync; the setTimeout loop is simply being used to make sure the display is updated (approximately) once a second. If it isn't actually quite exactly once a second, it doesn't really matter.
I hope that helps explain things a bit better.
When the Timer() function is called, it schedules itself to be run again one second later. The end result is once every second, Timer() updates the show element with the current time. (I have no idea why it's assigned to t, unless t is used in some other code on the page.)
The line starts The function again after one second.