I am executing setTimeout function in a page which loads via ajax call. but if i click the link to load the page again, i afraid the last setTimeout call still continues and the number of intervals of the calls set by setTimeout executes multiple times.
tried this is the remote page:
var RefreshInterval = null;
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
RefreshInterval = null;
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
declare var RefreshInterval = null; outside of page loaded by ajax and use this code on the page:
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
if i don't want to declare it in parent page, here is the solution i found:
//Clear previously loaded calls if exists
try{ clearTimeout(wifiRadarRefreshInterval); }catch(e){}
var wifiRadarRefreshInterval = null;
function somefunction(){
....
setNextRefresh();
}
function setNextRefresh() {
try{
clearTimeout(wifiRadarRefreshInterval);
wifiRadarRefreshInterval = null;
wifiRadarRefreshInterval = setTimeout('somefunction();', 20*1000);
}
catch(e){
console.log(e.message + e.stack);
}
}
Do not use this
var RefreshInterval = null;
clearTimeout(RefreshInterval);
You are actually assigning a null and then trying to clear it. Which will not work, The timeout must be cleared by using the clearTimeout and by passing the variable which was assigned to the setTimeout. Here you will end up passing a null so the timer is never cleared.
Here is a small sample which will demonstrate a fix to your problem JS Fiddle
So insted of setting the variable to null and then trying to clear it, Just check if the variable is not defined and if it is defined clear it, else move on. Use the code below, Also you must remove the top two lines as mentioned
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
Click on the button say like 4 times, The output should be printed only once. That is if the ajax call is made 4 times the set time out must execute only once. Check below snippet for demo
var clickCount= 0; // just to maintain the ajax calls count
function NewPageSimilator(clicksTillNow) { // this acts as a new page. Let load this entire thing on ajaX call
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
function setNextRefresh() {
window.RefreshInterval = setTimeout(printTime, 3000); //20*1000
}
function printTime() {// dumy function to print time
document.getElementById("output").innerHTML += "I was created at click number " + clicksTillNow + '<br/>';
}
setNextRefresh();
}
document.getElementById("ajaxCall").addEventListener("click", function() { // this will act as a ajax call by loading the scripts again
clickCount++;
NewPageSimilator(clickCount);
});
document.getElementById("clear").addEventListener("click", function() { //reset demo
clickCount = 0;
document.getElementById("output").innerHTML = "";
});
<p id="output">
</p>
<button id="ajaxCall">
AJAX CALL
</button>
<button id="clear">
Clear
</button>
Related
I am creating a landing page which should exist in two languages. The texts that should be shown are in two JSON files, called accordingly "ru.json" and "en.json". When a user clicks on the "Change language" button, the following function is executed:
function changeLang(){
if (userLang == 'ru') {
userLang = 'en';
document.cookie = 'language=en';
}
else {
userLang = 'ru';
document.cookie = 'language=ru';
}
var translate = new Translate();
var attributeName = 'data-tag';
translate.init(attributeName, userLang);
translate.process();
}
Where Translate() is the following:
function Translate() {
//initialization
this.init = function(attribute, lng){
this.attribute = attribute;
if (lng !== 'en' && lng !== 'ru') {
this.lng = 'en'
}
else {
this.lng = lng;
}
};
//translate
this.process = function(){
_self = this;
var xrhFile = new XMLHttpRequest();
//load content data
xrhFile.open("GET", "./resources/js/"+this.lng+".json", false);
xrhFile.onreadystatechange = function ()
{
if(xrhFile.readyState === 4)
{
if(xrhFile.status === 200 || xrhFile.status == 0)
{
var LngObject = JSON.parse(xrhFile.responseText);
var allDom = document.getElementsByTagName("*");
for(var i =0; i < allDom.length; i++){
var elem = allDom[i];
var key = elem.getAttribute(_self.attribute);
if(key != null) {
elem.innerHTML = LngObject[key] ;
}
}
}
}
};
xrhFile.send();
}
Everything works fine, however, when a user opens the page for the first time, if his Internet connection is bad, he just sees the elements of the page without text. It is just 1-2 seconds, but still annoying.
The question is, is there any way to check the text has loaded and display the page elements only on this condition?
You can use $(document).ready() in this way
$(document).ready(function(){
//your code here;
})
You can use the JavaScript pure load event in this way
window.addEventListener('load', function () {
//your code right here;
}, false);
Source: Here
translate.process() is asynchronous code which needs to make a call to a server and wait for its response. What it means is that, when you call this function, it goes in the background to go do its own thing while the rest of the page continues loading. That is why the user sees the page while this function is still running.
One minimal way I can think around this is by adding this to your css files in the head tag.
body { display: none }
And then, under this.process function, after the for loop ends, add
document.body.style.display = 'block'
If you want to suppori IE8:
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
// run some code.
}
}
Put the code you want to execute when the user initially loads the page in a DOMContentLoaded event handler like below:
document.addEventListener('DOMContentLoaded', function() {
console.log('Whereas code execution in here will be deffered until the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.');
});
console.log('This will log immediatley');
It's important to note that DOMContentLoaded is different than the load event
i have 3 divs , i want that on first time the page is loaded the function init runs,not again after tht on refresh or reload of page. but its not working below is my code, it runs the code even on refresh or reload of the page.
function _(x){
return document.getElementById(x);
}
$(document).ready(function(){
init();
});
function init() {
_("page1_id").style.display = "none";
_("page2_id").style.display = "none";
_("page0_id").style.display = "block";
}
i am a newbie so kindly share the code tht i need to add or change..thank u
Set a cookie init_run = true
then check it before running init()
or inside the init function:
function init (){
if ( cookie is set )
return;
...
}
The JS below runs accordingly, but it never hits the last function (showAllTabIdRedirect). Any idea why? Is it my syntax? I am trying to run the first function that grabs the primary tab id and then use that to pass along some other functions. In the end, I would redirect the user as well as refresh a specific tab.
<script>
function refreshDetailsTab() {
sforce.console.getEnclosingPrimaryTabId(focusDetailSubtabRedirect);
var formsId;
var currentUrl = window.location.href;
if (currentUrl) {
formsId = currentUrl.split('?formId=')[1];
} else {
return;
}
window.location = '/' + formsId;
debugger;
};
sforce.console.getEnclosingPrimaryTabId(focusDetailSubtabRedirect);
var focusDetailSubtabRedirect = function showTabIdRedirect(result) {
// window.onload = function showTabIdV1(result) {
//alert('2222');
var primaryTabID = result.id;
sforce.console.getSubtabIds(primaryTabID , showAllTabIdRedirect);
debugger;
}
var showAllTabIdRedirect = function showAllTabIdRedirect(result2) {
// alert('33333');
var firstSubTab = result2.ids[0];
sforce.console.refreshSubtabById(firstSubTab, false);
debugger;
//alert('Subtab IDs=====: ' + result.ids[0]);
};
window.onload = refreshDetailsTab;
</script>
You can check for successful completion of those methods. It's possible 'getSubtabIds' was at halt for some reason and that would cause the failure of calling the callback function 'showAllTabIdRedirect '.
See the documentation here for getSubtabIds
I think it has something to do with the window.location triggering first. It redirects the user before the other JS can load.
My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.
I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.
So far I'm able to set a time after which the user will be redirected to root path with the following script:
var delayedRedirect = function (){
window.location = "/";
}
var delay = 10000;
$(document).ready(function() {
setTimeout('delayedRedirect()', delay);
});
I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.
$('#btn-persist').click(function() {
delay = 3000;
// or calling again setTimeout('delayedRedirect()', delay);
});
But I noticed that changing the variable won't affect the setTimeout function that has already been called.
I've also tried to use the clearTimeout function as below without success
var delayedRedirect = function (){
window.location = "/persists";
}
var delay = 3000;
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
var stopRedirect = function (){
clearTimeout(triggerRedirect);
}
$(document).ready(function() {
triggerRedirect();
$('#btn-persist').click(function() {
stopRedirect();
});
});
I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.
At the same time, I don't want to stop any other JS functions that are running in parallel.
Do you see a better solution to achieve this?
The main problem why clearTimeout is not working. because you are clearing a anonymous function instead of a setTimeout variable
change this
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
to this
var triggerRedirect = setTimeout('delayedRedirect()', delay);
Edit:
also change this (if you want to restart the inactive redirect trigger)
$('#btn-persist').click(function() {
stopRedirect();
});
to this
$('#btn-persist').click(function() {
stopRedirect();
triggerRedirect();
});
main question
Is there a javascript way to identify if we are accessing a page for the first time or it is a cause of a back?
My problem
I'm implementing html5 navigation in my ajax driven webpage.
On the main script, I initialize a variable with some values.
<script>
var awnsers=[];
process(awnsers);
<script>
Process(awnsers) will update the view according to the given awnsers, using ajax.
In the funciton that calls ajax, and replaces the view, I store the history
history.pushState(state, "", "");
I defined the popstate also, where I restore the view according to the back. Moreover, I modify the global variable awnsers for the old value.
function popState(event) {
if (event.state) {
state = event.state;
awnsers=state.awnsers;
updateView(state.view);
}
}
Navigation (back and forth) goes corectly except when I go to an external page, and press back (arrving to my page again).
As we are accessing the page, first, the main script is called,the valiable awnsers is updated, and the ajax starts. Meanwile, the pop state event is called, and updates the view. After that the main ajax ends, and updates the view according to empty values.
So I need the code:
<script>
var awnsers=[];
process(awnsers);
<script>
only be called when the user enters the page but NOT when it is a back. Any way to do this?
THanks!
Possible solution
After the first awnser I have thought of a possible solution. Tested and works, whoever, I don't know if there is any cleaner solution. I add the changes that I've done.
First I add:
$(function() {
justLoaded=true;
});
then I modify the popState function, so that is in charge to initialize the variables
function popState(event) {
if (event.state) {
state = event.state;
awnsers=state.awnsers;
updateView(state.view);
} else if(justLoaded){
awnsers=[];
process(awnsers);
}
justLoaded=false;
}
Thats all.
what about using a global variable?
var hasLoaded = false;
// this function can be called by dom ready or window load
function onPageLoad() {
hasLoaded = true;
}
// this function is called when you user presses browser back button and they are still on your page
function onBack() {
if (hasLoaded) {
// came by back button and page was loaded
}
else {
// page wasn't loaded. this is first visit of the page
}
}
Use cookie to store the current state.
yeah! This is what I have:
var popped = (($.browser.msie && parseInt($.browser.version, 10) < 9) ? 'state' in window.history : window.history.hasOwnProperty('state')), initialURL = location.href;
$(window).on('popstate', function (event) {
var initialPop = !popped && location.href === initialURL, state;
popped = true;
if (initialPop) { return; }
state = event.originalEvent.state;
if (state && state.reset) {
if (history.state === state) {
$.ajax({url: state.loc,
success: function (response) {
$(".fragment").fadeOut(100, function () {
$(".fragment").html($(".fragment", response).html()).fadeIn(100);
);
document.title = response.match(/<title>(.*)<\/title>/)[1];
}
});
} else { history.go(0); }
else {window.location = window.location.href; }
});
And:
$.ajax({url:link,
success: function (response) {
var replace = args.replace.split(",");
$.each(replace, function (i) {
replace[i] += ($(replace[i]).find("#video-content").length > 0) ? " #video-content" : "";
var selector = ".fragment "+replace[i];
$(selector).fadeOut(100, function () {
$(selector).html($(selector,response).html()).fadeIn(100, function () {
if (base.children("span[data-video]")[0]) {
if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
$("#theVideo").html("");
_.videoPlayer();
} else {
_.player.cueVideoById(base.children("span[data-video]").attr("data-video"));
}
}
});
});
});
document.title = response.match(/<title>(.*)<\/title>/)[1];
window.history.ready = true;
if (history && history.pushState) { history.pushState({reset:true, loc:link}, null, link); }
}
});