Reputation: 361
I have a website that makes an ajax call and then loads a gif to show static on a TV. But right now the ajax calls don't take enough time for the effect to really pop. So I was wondering if there is a way to set the minimum time the ajax call will take?
You can see the website I am trying to make to get a better idea of what I am doing. Try clicking the right picture frame or the phonograph on the table.
<script type="text/javascript">
var minDelay = 1000;
var start = new Date();
$.get("form.html", function(result) {
callback($(result).find("#contact"));
var end = new Date();
var timeInMilliseconds = end - start;
if (timeInMilliseconds < minDelay) {
setTimeout(function() { callback(result); }, minDelay - timeInMilliseconds );
}
else callback(result);
});
$.get("music.html", function(result) {
callback($(result).find("#music"));
var end = new Date();
var timeInMilliseconds = end - start;
if (timeInMilliseconds < minDelay) {
setTimeout(function() { callback(result); }, minDelay - timeInMilliseconds );
}
else callback(result);
});
function callback(result) {
$("#screen").html(result);
}
</script>
Upvotes: 2
Views: 1989
Reputation: 102753
You can time the start and end points, and then add another delay if it's below a certain threshold (using setTimeout
). Something like this:
var minDelay = 1000;
var start = new Date();
$.get(url, function(result) {
var end = new Date();
var timeInMilliseconds = end - start;
if (timeInMilliseconds < minDelay) {
setTimeout(function() { callback(result); }, minDelay - timeInMilliseconds });
}
else callback(result);
});
function callback(result) {
// Ajax response handling here ...
}
Edit I'm not sure you can achieve this using JQuery's load
(per the docs, the target gets updated immediately after the response is received from the server). I'd suggest converting the load
calls into gets
. Ie, this:
$("#screen").load("form.html #contact");
Should become this:
$.get("form.html", function(result) {
callback($(result).find("#contact"));
});
And the callback
function I made up above should then populate the target of load
.
function callback(html) {
$("#screen").html(html);
}
Upvotes: 6
Reputation: 5891
You could use a setTimeout()
method in the ajax callback method to simulate a delay?
Pretty cool website btw!
Sample code:
var minDelay = 500;//half a second
setTimeout(DelayTimePassed, minDelay);
//make Ajax Call
function DelayTimePassed()
{
if(dataAvailable)
//show Data
else
//show data as soon as available
}
function AjaxCallback()
{
if(showDataAsSoonAsAvailable)
//Show Data Now
else
dataAvailable=true;//show data after time delay passes
}
Hope that makes sense to you - two methods check a couple of global bool variables to decide when to show the data.
Upvotes: 1