How to handle (a lot) timers in javascript - javascript

My situation is the following: People connect to my server and my server does store some information about the users which connected. For each connected user I have to handle 3 events on different times. So I thought about how to handle this is a good way. I had 2 different approaches in mind.
Creating a timer for each users event and that's it. Then my callback will be fired when it's time
Storing the timestamps on which the events should get fired and going through these timestamps every second and check if something need to get called
Which way would be the better to do this? Is there a general approach how to deal with scenarios like this?

Is there any reason to think that node won't handle the timers well? Definitely your first approach should be #1 -- use a timer for each event.
If for some reason that won't work then use a heap of timers. The root of the heap is always the closest timer to expire, and when that expires you go thru the heap, handling all the timers that expired (there may be more than 1), and then set a single timer to the next expiry time.

Related

A better approach to request data from server every x minute

I know that I can use setInterval to send a request to server every 1 minute to see if something new added to the database so I can fetch it and update the UI according to this
but for what I've read from different article I got confused some say it's bad practice and other use it
SO I'm asking here to see if there's better approach to accomplish this or setInterval will handle the mission without any issues
Well If you had to know if something has changed I would think about using sockets is a better choice. Of course if your server is ready to implement this kind of mechanism.
If you don't have an opportunity to change logic on the server (third-party API or something) setTimeout on practice most common solutions.
But with this kind of solutions you have some caveats:
you should handle by yourself when to clear your timeout; if you don't then you'll have a memory leaks at least;
something would never change, big amount of data - this kind of optimizations you need to implement with caching strategies;
not sure about security - servers can block your app because of DDOS in the case when a lot of your users work with this service;
setTimeout by itself is ok. Depends on your situation if there is better or more appropriate solutions.
You may configure a simple cronjob.
Whether you use it from your VPS or shared hosting (most of them have cron installed), whether you may use a free online service like cron-job.org.
No problem with setInterval and setTimeout but don't forget JS is mono-thread and chosing the one that corresponds to our needs, given that the difference is important between them.
This interesting point not from me :
The setInterval thing is less of a performance tip but more of a
concurrency best practice. setInterval has the potential to execute
code prematurely to when you're expecting.
E.g.,
function doSomething () {
// I take 500 ms to run
}
doSomething();
setInterval(doSomething, 150);
This bit of code will run then next iteration doSomething immediately
after it's finished executing the current iteration. The interval
timer never stops! This has the potential to freeze your runtime
environment by continuously running its code and not allowing the
system to do other things.
function doSomething () {
// I take 500 ms to run
setTimeout(doSomething, 150);
}
doSomething();
Even though this looks essentially the same the difference is that
doSomething will always wait 150 ms after running before requeuing the
next iteration for execution. This allows the system to run other
operations and prevents your runtime from being locked up.
https://www.reddit.com/r/javascript/comments/51srsf/is_it_still_true_that_we_shouldnt_use_setinterval/

Best way to program multiple alarms

I am creating an application that allows users to set multiple alarms.
The two ways I can think of doing is:
Store alarms as rows in a table and have a cron job check them every
minute. However, this means that the alarms will only be checked
every minute while some users may want it to be checked at a finer
resolution.
Create a new timer object for each new alarm that will call itself
with a setTimeout function. But if the app crashes then the alarms
are lost.
You can give a try to node-scheduer.
Very much similar to the cronjob. But the application must be kept on running.
It executes an event on a given interval. Make sure the job is executed after the desired interval every time and Put the alarm functionality there.

In Node.js, is setTimeout reliable?

I need to perform many "setTimeouts" 60 seconds. Basically, I'm creating a database record, and 60 seconds from now, I need to check whether the database record was changed.
I don't want to implement a "job queue" since it's such a simple thing, and I definitely need to check it around the 60 second mark.
Is it reliable, or will it cause issues?
When you use setTimeout or setInterval the only guarantee that you get is that the code will not be executed before the programmed time.
It can however start somewhat later because other code that is being executed when the clock ticks (in other words other code will not be interrupted in the middle of the handling of an event to process a timeout or interval event).
If you don't have long blocking processing in your code it means that timed events will be reasonably accurate. If you are instead using long blocking calls then probably node is not the correct tool (it's designed around the idea of avoiding blocking "synch" calls).
you should try WorkerTimer.js it is more good for handling background processes and more accurate than the traditional setInterval or Timeout.
it is available as a node.js npm package.
https://www.npmjs.com/package/worker-timer

Javascript Timed Notifications - setTimeout, setInterval

I am creating a web app that allows users to manage a calendar (CRUD events, tasks, reminders etc...)
And I am trying to implement a feature where they will receive a popup reminder x-minutes before the event/task. From my understanding there is really only one way to do this with javascript:
On login, check for any upcoming events in the database (say in the next 12 hours) and create a setTimeout for the next event, when that setTimeout executes, check again for next event and so on...
My question is, will having multiple setTimeouts (10+) running in the background during user interaction slow down the performance of my app?
Is there a better way to handle popup notifications on the client side? Push Notifications? Any suggestions would be greatly appreciated!
My question is, will having multiple setTimeouts (10+) running in the background during user interaction slow down the performance of my app?
In those numbers, no. (Depending on how + the + in 10+ is. I mean, I expect a million probably would be an issue.)
The other approach would be to have a single timer that you use (say, per minute) to check for notifications that should occur as of that minute. E.g.:
function notifyForThisMinute() {
// Notify user of things we should notify them of as of this minute
// ...
// Schedule next check for beginning of next minute; always wait
// until we're a second into the minute to make the checks easier
setTimeout(notifyForThisMinute, (61 - new Date().getSeconds()) * 1000);
}
notifyForThisMinute(); // First call starts process
This depends on the browser (or more specifically, it's javascript engine) and apparently even OS.
Neil Thomas (while working on GMAIL mobile) and John Resig have analyzed timers.
One of the more noticeable things to look out for is how often the timer runs per given time-interval (say every 200ms or once every 10 minutes..).
Thomas:
With low-frequency timers - timers with a delay of one second or more - we could create many timers without significantly degrading performance on either [an Android G1 or iPhone 3G]. Even with 100 timers scheduled, our app was not noticeably less responsive. With high-frequency timers, however, the story was exactly the opposite. A few timers firing every 100-200 ms was sufficient to make our UI feel sluggish.
Thomas:
Keep in mind that this code is going to execute many times every second. Looping over an array of registered callbacks might be slightly "cleaner" code, but it's critical that this function execute as quickly as possible. Hardcoding the function calls also makes it really easy to keep track of all the work that is being done within the timer.
Resig:
Once you start moving into the range of 64-128 simultaneous timers, you’re pretty much out of luck in most browsers.
One might also have a look at Chronos

What happen if I use setInterval to call ajax every 3 second or less?

I have a very short question. What happen if I use setInterval method to call an ajax function like checking message in inbox every 3 second (or if I can do in every 1 second would be nice!)
Well this is what I use:
setInterval(function() {
chk_inbx (var1, var2);
}, 8000);
I call this function every 8 second right now. I see no problem. (or maybe I don´t have so many users right now)
But what happen if I change it from 8000 to 3000 or even 1000 ?
UPDATE
I have test the polling (LONG POLLING (in php) starts hanging after 5 requests to database
)
I wonder what ´s diferences between setTimeout and setTimeout with polling.
What I understand is in php file they put the sleep(); function and use timestamp
to determin if the data is old or not.
But mine, I use N nd Y to determine if msg is read or not. if N then show the rowCount.
So what is the different ? can anyone help me ?
It could cause issues if the request takes longer to complete than your polling time. The duration of the request will depend on both your user's network speed and geographical location. Browsers will limit the number of concurrent requests, but they will keep queueing the new requests and the queue will grow to an unreasonable size, possibly slowing down or even crashing some browsers.
There are better ways to achieve what you want to do. The most common and cross-browser (websockets could also solve this problem in modern browsers) way is to use long polling.
With long polling you send a request as soon as you receive a response, so you are always polling continuously. The web server handles the process idling and repeated checks for new messages without generating a response until either a timeout (you can pick something like 30 seconds) or there is new data to inform the browser about.
You should avoid using setInterval() in this way.
The problem with setInterval() is that it keeps firing the event every 3 seconds (or whatever), even if the previous event hasn't finished yet.
If your response time is slower than the interval time, this can cause major problems with requests piling up on top of each other and maybe not even responding in the same order that they were requested.
This will become more and more noticeable the smaller the interval you set, but it can be a problem even for big intervals if you have any kind of blocking event in your JS code - an alert() box would be the classic example - as you can end up with large numbers of interval events piling up waiting for the alert to be cleared, and then all firing at once.
A better solution is to use a self-firing setTimeout().
This would use setTimeout() to start the event sequence, which then calls another identical setTimeout() call internally when its event is completed. This ensures you will never have multiple events piling up like you can with setInterval().

Categories

Resources