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
CodePudding user response:
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.
CodePudding user response:
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/