What Javascript event can I use for handling real time updates on a web page with ajax?
For example; Mouse_move would create frequent ajax post requests. I need a timer event, like in each 5 seconds, update notifications, check if new notification available.
Use the setTimeout function and replace alertMsg() with your ajax function. See the tutorial here: http://www.w3schools.com/js/js_timing.asp
function timeMsg()
{
var t=setTimeout("alertMsg()",5000);
}
function alertMsg()
{
alert("Hello");
}
You don't need events at all. See setTimeout or setInterval.
Related
Working on a platform, to enable auto-ticketing functionality. For which a REST API request is used for ticket creation. Unfortunately, there are 2 requests popping simultaneously, which results in creating duplicated tickets.
How to handle such case and send only one of these requests?
Tried adding the 2nd request in the response callback of the first, though this does not seem to work.
if (flag == 1){
logger.debug("Node-down alarm-Request raised - +sitn_id);
clearTimeout(mouseoverTimer);
mouseoverTimer = setTimeout(function(){
logger.debug("Inside Call back function - ");
//function call for ticket creation
incidentRequest(sitn_id,confUtil.config.mule_url);
}, 10);
You really should show more of the code that makes the request, though it seems as if you are doing some ajax inside your 'incidentRequest', so I will presume that (if that isn't what you are doing, then please, show your code....) - and since you tags say javascript and jquery - well, here goes...
To stop the 'double send' in an AJAX call, it is simple:
function incidentRequest(sitn_id,confUtil.config.mule_url){
// stop the double by clearing the cache
$.ajaxSetup({cache: false});
// continue on with the AJAX call
// presuming the url you want is confUtil.config.mule_url
// and the data you want to send is sitn_id
$.post(confUtil.config.mule_url, 'sitn_id=' + sitn_id, function (data) {
// do cool stuff
});
}
Hopefully that will help you get moving. If not, then we will need more code of what is going on around all this.
This question already has answers here:
Cancel/kill window.setTimeout() before it happens
(2 answers)
Closed 7 years ago.
Disclaimer : I'm not super proficient in Javascript and there's this small JS code part in my .net program.
I have 2 dropdown lists, ReportList and YearList. The first one's selected value dynamically populates the second dropdown list using AJAX. The problem is, each time a ReportList is selected it makes a query to a database. There can be at least 200 entries in ReportList and when a user uses the mousewheel on the dropdownlist, the application, as is, makes hundreds of query in a short amount of time and crashes the database. So far I have this
$('#ReportList').change(function () {
setTimeout(function () { PopulateYearsDropdownList() }, 2000);
});
I've played with stopPropagation() and it didn't work. I can't test it very efficiently since even the test DB is hosted and maintained by someone else.
I'd like to be able to scroll through without prompting as much queries as the amount of reports that have gone through. I was thinking of adding a small delay, with each function ".change" cancelling the last function call.
I think this wasn't really thought through from the beginning, but I want to fix this in the small amount of time I have.
I'd suggest assigning setTimeout to a variable (with proper scope accessibility) and using clearTimeout to stop the timeout.
To read more about setTimeout and clearTimeout.
An example would look like:
var myTimeout;
$('#ReportList').change(function () {
if (myTimeout) clearTimeout(myTimeout);
myTimeout = setTimeout(function () { PopulateYearsDropdownList() }, 2000);
});
You should either save the responses to the memory or use $.ajax's caching abilities. The latter needs that your server sends the response with proper caching headers
Not 100% sure what you are trying to do, but you can set your timeout to a variable, and then at another point in time clear the timeout.
var myTimeout = setTimeout(PopulateYearsDropdownList(), 2000);
//...some more code
clearTimeout(myTimeout); //cancels the original setTimeout
You can also use .abort() to cancel your AJAX request How to cancel/abort jQuery AJAX request?
I have a page with a list of items for the user to complete in a queue. Items get added into the database, and I need this list to be updated and reflect those changes on a regular basis (perhaps every minute).
I don't want to add a meta refresh to the page, because I want to avoid reloading the page. I already have a function that updates the list via ajax, so I'd like to call this function every minute.
Once the page is initially loaded, how can I repeatedly call this function without doing a blocking javascript loop? Is there a way to pause the setInterval or something to allow the rest of the queue pool to execute?
I'm worried about this happening:
$('document').ready(function () {
setInterval( function() {
updateList();
}, 60000);
}
A while(true) loop will indeed block the execution of all other scripts. setInterval will not.
The ideal solution would be a web socket like socket.io. With this, you could have something as simple as
socket.on("add", function (msg) {
addItem(msg);
}).on("removeItem", function (msg) {
removeItem(msg);
})
Then, on your server, you could simply socket.emit("messageType", msg);. This would prevent you from having to constantly poll the server with AJAX.
However, if that is not possible, you can fix your code with
$(document).ready(function () {
var updateInterval = setInterval(updateList, 60000);
// to clear interval: clearInterval(updateInterval);
})
where updateList is your function to poll the server via AJAX and append whatever tasks are received to the page.
You can use any of the following two:
setTimeout(expression, timeout); which executes the code/function once after the timeout. It is non blocking so you don't have to put it in a loop. You can call itself to make it execute infinitely.
function updateFunction() {
setTimeout(function() {
//update the page here
updateFunction();
}, 1000);
}
Or you can use setInterval(expression, timeout); which executes the code/function in intervals, with the length of the timeout between them.
setInterval(function() {
//update the page here
}, 1000);
Summing up from the comments:
You should get rid of while(true), it is blocking the rest of the code.
The setInterval() will be executed every 1min. anyway.
Note that after removing the while, the setInterval() will not block the rest of the code.
I'm sending an ajax request to the server on user's input to an <input> element, like this:
$('#my-input').bind("input", function(event){
// here's the ajax request
});
What bothers me is that it send unnecessarily many requests on every user's keyup, meaning that if the user types very fast, there are many unnecessary requests. So I get the idea that there should be a certain delay/timeout, which waits a certain time (50 miliseconds?) for the user to stop typing before sending the ajax request. That would be one problem solved.
But what about cases when the first ajax request haven't been completed before sending another request? (Typing 60 ms / char while ajax request taking 300 ms).
What is the best way to solve this problem (both idea- and code-based)?
You can use throttle function in underscore library. As its documentation says:
Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.
Even if you don't want to introduce a new library, you can still get idea about how this function works from its source code. In fact, a simple version of throttle function could be:
function throttle(func, delay) {
var timeout = null;
return function() {
var that = this, args = arguments;
clearTimeout(timer);
timeout = setTimeout(function() {
func.apply(that, args);
}, delay);
};
}
This jQuery throttle-debounce plugin is also helpful. Especially, the debounce function seems more suitable to your needs than throttle function according to its author:
Debouncing can be especially useful for rate limiting execution of handlers on events that will trigger AJAX requests
You could just use the setTimeout function. Every so often, see if the text hasn't changed, and if it hasn't, then process accordingly.
setTimeout(function() {
// Do something after 1 second
}, 1000);
You can set async: false in your ajax request so it will process second ajax call only after completion of first ajax request.
I'd go with #HuiZeng's answer, but just in case you want a slightly modified version.
Steps
Listen to keydown using a setTimeout that you can clear.
When it fires, check if you have a previous request in queue, if so abort it and fire a new one
Example:
var inputTimer = 0, req;
function onInput(e){
clearTimeout(inputTImer);
inputTimer = setTimeout( function(){
// You have access to e here
// Cancel any previous requests
req && req.abort();
req = $.ajax({/*...Do your magic here :)*/})
}, 100)
}
OK, So I am creating a entire web app using AJAX with some local storage etc.
The issue I am having is sometimes I double click, or click tabs back and forth quickly which invoke a $.post call.
Problem lies when the callbacks are fired, they are called back and keep overwritting eachother until the last call has came back.
Obviously that is a problem. What I need to do is cancel current POST calls and just get the last callback.
I have tried:
// Make Call:
if(call != undefined){
call.abort();
}
var call = $.post(url,{do:'stuff'},function(response){
// callback stuff:
},'json');
Keeps saying its undefined regardless, I rather use .POST than .AJAX if possible.
Thanks for your help in advance!
Simply unbind the click event on click, re-bind it on callback.
One thing you can do if canceling doesn't catch all your pending XHRs: increment a counter and pass it to your backend to keep old responses from clobbering new ones. Just have your backend include the counter value in the response, and then your callback can compare it to the local counter before overwriting.