I have an variable
var IsAjaxing;
I set it to true everytime a ajax is fired on the page. And then set it to false when ajax is finished;
I am building a SafeAjaxing event so work would only be done when the page is not ajaxing:
// safe-ajaxing: Triggers when no ajax is running
$($fieldRenderPageDOM).on("safe-ajaxing", '.field-render', function(e, work) {
$.when({ IsAjaxing: false }).done(work);
});
This doesn't seem to wait, work is always called immediately.
It would be called like this:
$fieldDOM.trigger("safe-ajaxing", function () {
$fieldDOM.trigger("do-work");
$fieldDOM.trigger("do-some-more-work);
});
You should use promises for this purpose:
var IsAjaxing = function(){
var defer = $.Deferred().resolve();
return {
On: function(){
defer = $.Deferred();
},
Off: function(){
defer.resolve();
},
Promise: function() {
return defer.promise();
},
IsOn: function() {
return defer.state() == "pending";
},
IsOff: function() {
return defer.state() != "pending";
}
};
}();
And then your event will be:
// safe-ajaxing: Triggers when no ajax is running
$($fieldRenderPageDOM).on("safe-ajaxing", '.field-render', function(e, work) {
$.when(IsAjaxing.Promise()).done(work);
});
Each time when you start ajax request run:
IsAjaxing.On();
Each time when you finish ajax run:
IsAjaxing.Off();
To check the current state of IsAjaxing, call the IsOn and IsOff function.
This might not be the best way, but it works.
You really should optimize the code i've written, but this is to get you started.
var isAjaxing = false;
var check = function(){
if(isAjaxing){
// do something
alert();
// freeze the checking
// manual restart is required
clearInterval(interval);
}
}
var interval = setInterval(check, 10);
// to demonstrate the variable change
setInterval(function(){
isAjaxing = true;
}, 3000);
This scripts checks if the variable is changed every 10 miliseconds.
Note: The clearInterval() function is used to stop checking.
I am building a SafeAjaxing event so work would only be done when the page is not ajaxing.
Don't build this yourself. Just use the builtin ajax events of jQuery, namely
ajaxStart "This event is triggered if an Ajax request is started and no other Ajax requests are currently running."
ajaxStop "This global event is triggered if there are no more Ajax requests being processed."
Related
In my Rails 5.2.2 app I am using Turbolinks.
I have discovered that when I leave a page, the functions that were started continues.
I have organised my functions below a return statement that checks the body class. In my example below, if the body class is not foobar the functions below do not run.
// assets/javascripts/pages/foobar.js
var goLoop;
$(document).on("turbolinks:load", function() {
if (!$("body").hasClass("foobar")) {
return;
}
return goLoop();
});
goLoop = function() {
return setTimeout((function() {
console.log("Hello");
return goLoop();
}), 1000);
};
First time I visit the page, the goLoop function is triggered.
When I follow a link away from the page, the function runs. If I had not used Turbolinks, this would not have happened.
If I follow another link back to the page, the function is triggered again, so now it runs twice.
How can I avoid this, without disabling Turbolinks?
Use the turbolinks:before-cache to teardown your timeout using clearTimeout. You will need to keep a reference of the current timeout ID. So your solution might look like:
var goLoop;
var timeout;
$(document).on("turbolinks:load", function() {
if (!$("body").hasClass("foobar")) {
return;
}
return goLoop();
});
goLoop = function() {
return timeout = setTimeout((function() {
console.log("Hello");
return goLoop();
}), 1000);
};
$(document).on("turbolinks:before-render", function() {
clearTimeout(timeout);
});
You can use PageVisibilityAPI to see is current page active or not.
and for the loop issue, you should check whether it's exist or not then run timeout function.
I have a setinterval that runes every 5 seconds. this works fine on page load.
I have the following scenarios:
Load page with interval (WORKS)
press button and load new content and stopp interval(WORKS)
Once the new content is no longer desiered, dissmiss it, return to first content and start interval again(DOES NOT WORK)
I have saftys suchs as events for window.blur that also stops the interval so that the browser does not commponsate for all the missing intervals if i would change tabs or something. Keep in mind that step 3 did not work BUT if i would after step 3 change a tab and then return to my original page(execute blur) the interval would start working again.
NOTE all content loading here exept page load is done with ajax calls.
My code:
initializing:
$.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function() {
$.automation.tanks.tableInit();
});
binding function:
bindIntervalEvent: function (target, url, callback) {
$(window)
.on("focus.mine",
function() {
$.automation.worker.setUpdateInterval(target, url, callback);
})
.on("blur",
function() {
$.automation.worker.stopUpdateInterval();
}).trigger("focus.mine");
}
interval function:
setUpdateInterval: function (target, url, callback) {
if ($.automation.globals.globalInterval.value.length === 0) {
$.automation.globals.globalInterval.value.push(window.setInterval(
function () {
var options = {
loadTarget: target
}
$.automation.worker.getView(url,
function() {
if (callback)
callback();
},
options);
},
5000));
}
}
the function that stops the interval:
stopUpdateInterval: function () {
if ($.automation.globals.globalInterval.value.length === 0)
return;
console.log("deleting");
for (var i = 0; i <= $.automation.globals.globalInterval.value.length; i++) {
window.clearInterval($.automation.globals.globalInterval.value[i])
$.automation.globals.globalInterval.value.splice(i, 1);
console.log($.automation.globals.globalInterval.value.length);
}
}
when stopping the interval i also remove the window bindings:
unBindIntervalEvent: function() {
$(window).off("focus.mine");
$(window).unbind("blur");
}
Back to step 3:
My sucess method in the callback to my getviewfunction is identical to what i execute in the beginning
code:
$(".updatelatest")
.on("click",
function () {
var _this = $(this);
var options = {
loadTarget:"#TanksContent"
}
$.automation.worker.getView("/Tank/GetTanks",
function (data) {
$(_this).switchClass("col-md-5", "col-md-1", 1000, function() {
$(_this).addClass("hidden");
$(".search").switchClass("col-md-5", "col-md-12", 1000, "easeInOutQuad");
})
$.automation.tanks.tableInit();
$.automation.worker.bindIntervalEvent("#TanksContent", "/Tank/GetTanks", function () {
$.automation.tanks.tableInit();
});
$(window).trigger("blur");
}, options);
});
but this does not start the interval. it is clearly initialized since it works when window.blur is executed for example when I change tab but for some reason this is not working beyond that.
i tried triggering the windows blur event and nothing happened, i tried triggering my custom window event "focuse.mine" but nothing happens.
I did not notice this while developing since I had firebug open and every time i checked scripts or css or the console the blur function was executed so I assumed that my code worked as intended but now that it is deployed I notice this.
My head is pounding beyond reason and I can't for figure out where I have gone wrong.
Well this was a fun one. I simply found that when calling the setUpdateInterval(); function directly it gave me the desiered result.
I realized that the reason I had them split like I did was becaouse of the blur event. "Focus.mine" is triggered to start the inteval again ocne a user comes back to the page.
I have a lot of buttons on my web app that request and post data to PHP to retrieve and update a database. I am struggling to create a universal way to prevent multiple button clicks when submitting forms, because I am using AJAX and Jquery.
This is my current implementation but I can't even tell if it works. It seems to work 99% of the time.
In my common functions.js file I have this function which is in the global scope
var canClick = true;
function buttonWithPromise(promise){
if(!canClick) return;
canClick = false;
promise.done(function(){
canClick = true;
});
}
Then any time I attach a .click to a dom element I do it like this:
$('body').on('click', '.table > .row', function(){
var nbr = $(this).attr('nbr');
buttonWithPromise(get_count(nbr));
});
And some function that might be called will have a deferred object.
function get_count(){
var defer = $.Deferred();
var options = "getCount"
Query.init(options)
.fetchData(function(data){ //Ajax data request
if(data){
}
defer.resolve();
});
return defer.promise();
}
Since this only sometimes works, I can tell it's wrong. Any advice for improvements?
Everything in Javascript is an object, yes? So why not:
$('body').on('click', '.button', function()
{
// Set default value of property
if(typeof this.isClicked === 'undefined')
this.isClicked = false;
// Check if button is working
if(this.isClicked)
{
// Send error to console if button is busy
console.log('Cannot click as a network action is occuring!');
}else
{
// Begin new network action if button is not busy
var self = this;
console.log('Begin network for: ' + $(this).text());
this.isClicked = true;
setTimeout(function()
{
// Reset button state once network action is done
console.log('End network for: ' + $(self).text());
self.isClicked = false;
//Call any callbacks/promises here
}, 5000);
}
});
Fiddle:
http://jsfiddle.net/mdLfug1t/
NOTE: I'm using setTimeout to simulate an ajax request
EDIT: Let me put this more into context:
function buttonWithPromise(promise)
{
if(typeof promise.canClick === 'undefined')
promise.canClick = true;
if(!promise.canClick) return;
promise.canClick = false;
promise.done(function()
{
promise.canClick = true;
});
}
The problem that you're running into is that "canClick" is global and so gets modified by every promise. You need to make it a property of a promise so that you can create infinite promises, each with their own instance of canClick.
The HTML code: <input id="goTOxQuestion">
The js code:
$("#goTOxQuestion").keyup(function(){
// send a XHR
})
If the input is 12345,it will send the XHR five times.In fact, I only want the XHR be executed when I have completed the input. I mean,there is no input( no keydown event )in 500 milliseconds, rather then it loses faocus.
My incomplete solution:
var isOver = false;
$("#goTOxQuestion").keyup(function(){
//...
setTimeout(function(){
if(isOver){
//send a XHR
}
},500);
})
$("#goTOxQuestion").keydown(function(){
isOver = false;
})
You can use a combination of setTimeout and clearTimeout like this:
var hTimeout;
$("#goTOxQuestion").keyup(function () {
if (hTimeout) {
clearTimeout(hTimeout);
}
hTimeout = setTimeout(function () {
// ajax code here
}, 500);
});
Demo here
Note that the order in which AJAX requests complete is not guaranteed and you will end up with "race conditions".
Regarding your comment, here is a solution from the top of my mind:
// initialize global counter
var xhrCount = 0;
// increment counter when you create an XHR
xhrCount++;
// pass the current value of this
// variable to the success function
// http://stackoverflow.com/q/1552941/87015
$.ajax("/url/", (function (myStamp) {
console.log("creating success callback #" + myStamp);
return function () {
if (myStamp === xhrCount) {
console.log("firing success handler");
} else {
console.log("suppressing success handler");
}
}
})(xhrCount));
Use setTimeout then:
$("#goTOxQuestion").keyup(function(){
setTimeout(function(){
// send a XHR
}, 1000);
})
The change event seems like a good fit for your needs :
$("#goTOxQuestion").change(function(){
// send a XHR
})
It will be triggered when the input looses focus and the input value was actually modified.
$(document).on('blur',"#goTOxQuestion",function(){
// send a XHR
});
I have the following (javascript/jquery) code to show a busy indicator (after a delay) while an image is loading:
function imgUpdate(arg) {
var loaded = false;
$("#image").one("load", function(){
loaded = true;
$("#busyIndicator").hide();
});
setTimeout(function(){
if (!loaded) {
$("#busyIndicator").show();
}
}, 250);
$("#image")[0].src = arg;
}
Sometimes, the indicator comes up and stays up. How is this possible if the browser's javascript engine is single-threaded? (This is on Firefox 3, by the way.)
One note: this seems to happen when the image being loaded is already cached.
Another note: if I log to my firebug console, all of the lines in imgUpdate are executed, but a log message inside the onload handler never prints on subsequent calls to imgUpdate.
Is there any other javascript on the page that breaks? If so, this may not be a race condition -- JS could simply stop executing before the busyIndicator is hidden again...
I'm hard pressed to replicate this.
Here is the implementation of what you're doing:
A version using caching:
http://jsbin.com/uwuho
A version with caching being prevented: (uses parameter to avoid caching)
http://jsbin.com/oguvi
Hit F5/Ctrl-F5 to see it go. (in particular with the version which prevents caching)
With or without caching neither version is doing what you'd described.
Your problem probably lies elsewhere.
Clearing the image's src tag seems to fix the problem:
function imgUpdate(arg) {
var loaded = false;
$("#image").one("load", function(){
loaded = true;
$("#busyIndicator").hide();
});
setTimeout(function(){
if (!loaded) {
$("#busyIndicator").show();
}
}, 250);
$("#image")[0].src = "";
$("#image")[0].src = arg;
}
You might want to clear the timeout in your callback so that it won't fire if the image is loaded.
var timer = null;
function imgUpdate(arg) {
var loaded = false;
timer = setTimeout(function(){
$("#busyIndicator").show();
timer = null;
}, 250);
$("#image").one("load", function(){
if (timer) {
clearTimeout(timer);
timer = null;
}
$("#busyIndicator").hide();
});
$("#image")[0].src = arg;
}