Javascript run function in background regardless the page - javascript

i need to run a function periodically regardless the page where i am. This function will get some data periodically.
I dont think that this works:
function myFunc()
{
//your code
}
//set the interval
setInterval(myFunc,2000) //this will run the function for every 2 sec.
Because it works only for the page where I am right now, so if i go to another page, function is not executed anymore.
I would like to write a function that start running when user is at index page and then is called periodically until user close the page.
Any idea? Thanks in advance!

That's not possible with javascript in the browser. When you navigate away from the page, the script will stop. You have to include a script on every page that initializes this periodical update. Or you could rewrite your application to a "single page application", which seems to be popular nowadays.

You'll need a backend application or cron-job to do that.
Another way do that would be to make an Ajax-only single page application. I guess twitter uses that model.

Depending on what your doing in the function you may be best to use a JS Worker which will run as a new thread and allow you to continue processing as much as you want in the background without having to worry about JS timeouts.
The main point here is what your asking for is near enough impossible within JS unless you use something similar to jQUery and dynamically load your pages in to a div? This would mean you still have the effect (visually) that you changing page but the browser only loads the data in.
Its very easy to in fact to load content in to a DIV using jQuery its:
$('#elementoloadid").load("/path/to/load");
You could achieve this without using jQuery but will take you longer.

Related

Language set up with out loading whole page

Are there any alternate way of below code to set app language? Below code refresh the whole page always that gives bad experience to users.
window.location.search = "sap-language=EN";
This is also one way to achieve.
sap.ui.getCore().getConfiguration().setLanguage("EN");
However, some standard controls after rendered don't change the labels. Let me know if there are any other way that help here because loading whole page doesn't make any sense.
You can use Ajax by getting all the new markup and replacing the existing content by the reloaded content.
It might create some issues with other running scripts like loading images and sliders etc that holds a reference to an element so you have to reinitialize every single script that is running on settimeout() on your page.
Moreover you can use jQuery Localisation plugin

How to stop scroll event function when the user move to another page

I am adding the scroll event in javascript for one of my pages. The code is like this:
document.getElementById("myProject").addEventListener("scroll", myFunction);
function myFunction() {
document.getElementById("scrollEvent").innerHTML = "These are all my projects so far";
}
So, when users start scrolling, they will see a text "These are all my projects so far".
My problem is how to stop showing this text when users move to another page.
Please help ( I am a verrrry fresh developer)
Thanks so much
A few thoughts.
Without knowing your dev environment (e.g. are you using MVC with a framework?), I will assume you are simply talking about separate/individual HTML pages.
Each HTML page can have its own javascript. Just like HTML and CSS, there is no need to have the same javascript functions on every page. (You don't have the same HTML content on every page, right?) Usually, we divide up the javascript into multiple files - some files are added to every page, some are specific to a certain page. It is easiest to have one (external) javascript file that you reference on every page, and then specific javascript code for each page - either in a second external file that is referenced, or on the HTML page inside <script>//js here</script> tags.
If the DIV with ID myProject is not on the other page, then the javascript won't do anything. However, it is not good to have broken javascript on a page, so make sure it is not included on other pages.
If you are using a framework, like CodeIgniter or ReactJS or Angular, please tell us so we can adjust our answers accordingly.
If the case is a switching between browser tabs, you can use two different events like below.
$(window).blur(function(e) {
// stop scroll event, when switching to another tab
document.getElementById("myProject").removeEventListener("scroll");
});
$(window).focus(function(e) {
// start scroll event
document.getElementById("myProject").addEventListener("scroll", myFunction);
});
I am not sure what you are actually looking for, because when user switch between tabs, he can not see the text anymore no matter there is a scroll event or not. If you are concern about performance, then the above solution would help.

Effectively and repeatedly updating DOM with data without breaking page

I'm creating a SPA which of course uses AJAX to dynamically load pages in a div. My layout is a side accordion menu where when you click on an item, it loads information on a div next to it. My problem is that if a person decides to click menu items as fast as they can per second, I start getting blank content in my pages. So my question is, what are some best practices (if any) to avoid pages breaking when you have people clicking so fast?
Things I'm doing for performance:
Using html templates and json files to build pages before application starts, keeping the (simple) pages in memory to grab - instead of calling ajax every click
For now, on each click I'm using at clearTimeout and setTimeout set to some milliseconds to slow down the process of switching pages - not ideal
Unfortunately, I can't post code because it's too long, but I'm hoping I can get some help with this information.
Thanks guys!
**Note: This is only front-end work, no databases because the load isn't heavy.
EDIT:
Here is a little snippet of my setTimeout and clearTimeout:
if (clickTimeout) { clearTimeout(clickTimeout); }
clickTimeout = setTimeout(function()
{
clickLink(menuItem.attr('href'));
}, 500);
I usually just disable the UI element that caused the event before sending the ajax, and then the client side code re-enables it after the data has arrived. This of course can only be done if you have code that runs when the data arrives. You might also be making mistakes when updating the DOM with the data if that is how you display it. Sometimes blank DIVs only appear after a while.
I think the title of the question is wrong and should be more along the lines of effectively repeatedly updating the DOM with data without breaking the page.

JavaScript's get-it-done nature

Is JavaScript intended to be running as little as possible on a website/webapp? By that I mean is the usual intention to run through all your js files as soon as the page loads and put them aside, and then when functions come up to execute them right away and be done with it?
I'm working on a project using google maps and I have a custom marker object scripted out, and a debugger has told me that the browser runs through all my js files before anything even appears on the page.
My problem comes in here: I wanted to animate certain markers to bounce up and down continuously with jQuery (similar to OS X icons in the dock) and my several attempts at infinite loop functions all just crash the browser. So I understand that the browser doesn't like that, but is there a way to have a simple script be repeating itself in the background while the user navigates the page? Or is JavaScript just not supposed to be used that way?
(I worked with Flash for a long time so my mindset is still there.)
Yes, Javascript functions should just do their bit and exit as soon as possible. The GUI and the scripts run on the same single thread, so as long as you are inside a Javascript function, nothing shows up in the browser. If you try to use an infinite loop, the browser will appear to freeze.
You use the window.setInterval and window.setTimeout methods to trigger code that runs at a specific time. By running an interval that updates something several times a second, you can create an animation.
You have to set a timer to execute a script after a defined time.
var timer = setTimeout(code, milliseconds);
will execute code in so-and-so milliseconds. Each execution of the script can set a new timer to execute the script again.
You can cancel a timed event using clearTimeout(timer).
Use setTimeout() or setInterval(). The MDC articles on it are pretty good.
You'll need to update inside of functions that run quickly, but get called many times, instead of updating inside of a loop.
Since you said that you are using jQuery, consider using its effects API (e.g., jQuery.animate()), it will make your life much easier!
Personally, I save as much code as possible for execution after the page has loaded, partly by putting all my <script>s at the bottom of <body>. This means a (perceived) reduction in page load time, whilst having all my JS ready to run when need be.
I wouldn't recommend going through everything you need to do at the beginning of the document. Instead, bind things to events such as clicks of buttons, etc.

How can I update a webpage when a change occurs on the server?

Is there a way to push pages on change rather than putting a timer on a web page to refresh every x mins? I guess what Im trying to do is not refresh an entire page when only a portion of it may have changed. I have seen on FB when an update happens, it has message saying new content available.
Perhaps you could MD5 a page then when an update happens the MD5 changes and the page could be checking this. Not exactly push but it would reduce the traffic of an entire page.
How can I update a webpage when a change occurs on the server?
a good practice to "reduce the traffic" is to load content through AJAX requests.
the "timer" you mentioned above is my preferred method with my previous comment and a bit of extra logic. This is know as long-polling.
One way is to watch for specific keyboard events and/or mouse events and update the page if certain criteria is met within those events.

Categories

Resources