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
Related
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/
For my webapp I'm going to need to have many timeouts running at once at any given point, possibly around 10,000-100,000. What I'm wondering is how well this function scales.
I don't need it to be that accurate, mostly accurate within 10-100 ms. Would it be better to have a single function run on an interval (say, to run every 50 ms), that checks the current datetime compared to the saved datetime and invokes the function if so?
Does anyone have any insight in to the underlying implement of setTimeout and can shed some light as to how well it can be used en-masse?
More questions I had: Does anyone know of a limit to how many timeouts can be running at once? Also, with both approaches I'm concerned about there not being enough time to process each timeout per interval and it getting "behind" in terms of triggering the timeout function in time.
Actually you cannot determine the exact interval between timeouts, because all it does is it pushes your callback to the callback queue after the threshold and when the event loop will get that callback, push to the call stack and execute it - is non-deterministic. The same is with intervals. You may appear in a situation, when, for example, 5 callbacks will be executed one after another without a delay. This is javascript ))
This is too long for a comment.
possibly around 10,000-100,000
Let's consider what this means. Say that each queued callback takes ~10ms to run, and you queue up 50,000 of them to run in 50ms. Only one of them can run at a time. So by the time the event loop even checks to see if it's time to run the 1000th callback, 10 whole seconds have passed. By the time you get to the 50,000th callback it will have been ten whole minutes! Now obviously if your queued callbacks take fractions of a millisecond that two order-of-magnitude dropoff makes the math a little less dismal, but if they have to do any I/O this probably isn't going to work and it probably won't work no matter what, at least not for a webapp that also has to serve clients.
I'm designing an app to run on very low spec machine..and i needed it to be efficient as possible..
I needed to issue around 10 intervals at every second that simply makes an ajax call.. and then does a few add/remove classes and (think of it as SERVER Status monitor)
I know in FLASH (oh good old flash days) having a lot of intervals can cause processor spikes .. so i'm very conservative with issuing setIntervals in AS 2.0 before.
I was wondering if this is the same case with JS? or is it alright for JS to have a bunch of intervals (that does lightweight tasks) running? I noticed a lot of sites do this , even facebook has tons of intervals running, loading scripts, etc..
And oh, for one interval, I wanted to run it at 50ms (it loads as status.php link) ... this ok?
I could probably optimize my interval calls, no problem but i'm just wondering how "heavy" or "lightweight" background intervals are in JS..
Thanks all
10 intervals at every second meaning a call every 100ms should not be an issue in my opinion, but if you ask me I would fire a call every 250ms.There is not much difference between the two that the user will notice.
Also make sure that there is a mechanism to handle long running response from server in case there is a delay and stop the interval firing if there is drag.
As a matter of personal feeling, I tend to prefer setTimeout over setInterval -- to the point I don't use setInterval at all.
The issue that you might run into is if one process takes longer than it should -- let me give you an imaginary situation:
window.setInterval(takes100msToRun, 50);
window.setInterval(takes50msToRun, 50);
window.setInterval(takes20msToRun, 50);
The problem is that the first interval will take longer than it should, so the second two interval requests are now behind and the browser will try to catch up by running them as quickly as then can. The second interval takes 50ms, -- so its still running behind when the third interval hits.
This creates an ugly situation that can lead to a lot of drag.
On the other hand, if you setTimeout, then you aren't say "Run this every 50 ms", but rather "Run another one of these 50ms from we finish." (Assuming, of course, that the functions set up another setTimeout to re-execute.)
It is absolute rubbish for things that need good clock timing, but its superior for everything else.
setTimeout and setInterval will affect performance, but little.
Since there are lots of functions triggered/listening/running in the browser.
Even a tiny operation like move your mouse to vote up for this answer, there are thousands of events got triggered, and tens of functions start running.
Don't use setInterval. As a matter of fact, the library underscore doesn't use it either.
See how they implement the _.throttle without setInterval.
http://learningcn.com/underscore/docs/underscore.html#section-66
I wonder if this code is going to put load on the client since the timeout is so long?
//and update this again in a bit
setTimeout(function() {
updateWeather(lat,lng);
}, 60000);
Not that code alone. The system idles for that one minute. As long as updateWeather doesn't have severe performance issues and the interval is short, setTimeout won't be a product (and I believe you mean setInterval, not setTimeout for recurring checks)
The 60 second timer is implemented by magic in the OS: it basically adds no CPU load during the 60 seconds it is waiting.
I guess updateWeather() is polling an external resource, so the answer to your question is a simple "no, it is fine". (As the weather does not change that often, I'd make it 5 minutes instead, see comment below on battery life.) (Even better: see if the weather data provider gives you a field telling you when the next update will be, and use a setTimeout based on that.)
In other situations, for instance if you have been collecting some kind of data for those 60 seconds, and then go and process it in one go, this could cause a peak of heavy load. Which might be noticed by the user (e.g. all animations go jerky once every 60 seconds). In that case it is better to use a 5 second timer, and process 5 seconds worth of data at a time.
Conversely, if you are using the network on a mobile device, you have to consider battery life: wake-up-and-find-a-connection can dominate. So extending a polling time from 60 seconds to 120 seconds can literally double battery life. Ilya Grigorik has a very good chapter on this in his book, High Performance Browser Networking, http://shop.oreilly.com/product/0636920028048.do
...here it is: http://chimera.labs.oreilly.com/books/1230000000545/ch08.html#ELIMINATE_POLLING
One thing to keep in mind, in addition to the other answers, is the affect that the closure of in-scope variables might have on memory performance. If you've got a gajillion objects being referenced by variables in the scope(s) above your setTimeout callback, those objects may live as long as the callback is queued. That is not something we can tell from the code you posted and so no answer can be definitively given to your question. Also, if your setTimeout is being called multiple times, it will create a closure for each one, effectively duplicating the environment and taking up your heap space.
The answer to your question depends on:
The device you execute this on
The environment - how many times do you execute this
A standalone setTimeout would not hurt the browser; however, if you are doing the same thing repeatedly, it would make a difference.
Have a look at the following website for more insights...
http://ejohn.org/blog/analyzing-timer-performance/
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().