I have a live updating div on my website. It works fine however the user always have to wait 5 seconds before it loads. Heres my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#div-id').load('/something.php');
}, 5000);
});
</script>
Is there a way I can load, it then wait 5 seconds and load it again? Instead of wait 5 seconds, load it, then wait again...
Thanks
Yes. jQuery's load() method has a complete callback function as a parameter:
.load( url [, data ] [, complete ] )
completeA callback function that is executed when the request completes.
Thanks to this we can create a recursive function which calls itself once complete (or in this case, after 5 seconds):
function loadContent(selector, path) {
$(selector).load(path, function() {
setTimeout( loadContent(selector, path), 5000 );
});
}
loadContent('#div-id', '/something.php');
What I've done here is move your content loading logic into a new function called loadContent, which accepts a selector and a path as its parameters. This function then triggers load() on the passed in selector, loading the passed in path. When the content has loaded a setTimeout function kicks in to trigger our loadContent function once again after 5000 millisecond (5 seconds).
Triggering loadContent() to begin with will fire our function off immediately, meaning you will not have to wait 5 seconds before the content first loads.
You have to run your ajax manually before first interval run.
<script type="text/javascript">
var loadContent = function() {
$('#div-id').load('/something.php');
};
$(document).ready(function() {
$.ajaxSetup({ cache: false });
loadContent();
setInterval(loadContent, 5000);
});
</script>
Just call the load once before
$('#div-id').load('/something.php');
setInterval(function() {
$('#div-id').load('/something.php');
}, 5000);
Related
My current script
setInterval(function() {
$.ajax({
url:"query.php?currency=<?=$currencycode;?>"
}).done(function(data) {
$("#value").attr("value", data).attr("size", data.length - 2);
});
},3000);
My webpage is only query the php file every 3 seconds but I want to make it query when the page is open and then to execute the loop refreshing the value for my input every 3 seconds. Now you have to wait 3 seconds untill the value is updated.
Separate the function from the setInterval() method and change the anonymous function to a named function.
Now all you have to do is invoke the function on page load as well as in setInterval() by just referencing the function name like this:
function someFunc() {
$.ajax({
url:"query.php?currency=<?=$currencycode;?>"
}).done(function(data) {
$("#value").attr("value", data).attr("size", data.length - 2);
});
}
someFunc(); // function will invoke on page load
setInterval(someFunc, 3000); // function will invoke after every 3 seconds
Check and run the Code Snippet below for a practical example of the above approach:
function someFunc() {
console.log("yes")
}
someFunc();
setInterval(someFunc, 3000);
I have an element that I want to have appear on my page after the user has been there for a few seconds. To achieve this, I used a sleep function and put it inside $(document).ready(). The idea is that the page will load and then the sleep will start. However what I'm seeing is that the sleep function is actually delaying the page load. Any idea what's wrong?
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
$(document).ready(function(){
if ( $( ".email_tab" ).length ) {
sleep(8000);
$(".email_tab").toggleClass("email_tab_hide").toggleClass("email_tab_appear");
}
});
The sleep function consumes your browser cpus and freezes it.
What you want is:
$(document).ready(function(){
if ( $( ".email_tab" ).length ) {
setTimeout(function() {
$(".email_tab").toggleClass("email_tab_hide").toggleClass("email_tab_appear");
}, 8000);
}
});
Your problem may be that when the document is ready, and email_tab length is zero, the setTimeout won't run.
In JS you should use setTimeout(); instead custom sleep() function
setTimeout(function(){
$(".email_tab").toggleClass("email_tab_hide").toggleClass("email_tab_appear");
}, 8000)
The $(document).ready callback actually runs before the page is fully loaded. It just ensures that the whole DOM is available for manipulating. Your sleep busy-loop then delays the rest of the loading process. You should use setTimeout instead.
i'm developing a web page which has a div with a class called headlines, it auto refreshes every 10 seconds and the problem is when whenever the data loads into the div, it blinks and i want to get rid of it.
$(document).ready(function() {
setInterval(function() {
$('.headlines').load('headlines.php');
}, 10000);
});
You're not going to get rid of the blinks if you use .load(). It blinks because it initializes a request, clears the .headlines, and loads the response from the server. This response is not instantaneous.
What you could do instead is use $.ajax, and in the success method, rewrite the content of .headlines.
Edit
Think of it this way... If the response were to never load, then when you use .load(), it would be waiting for a response. During that wait period, the .headlines would be indefinitely blank.
Instead, what you can do is wait for a server response outside the context of .headlines.
setInterval(function() {
$.ajax({
url: 'your-url.html',
success: function(res) {
$('.headlines').html(res.data);
}
});
}, 10000);
You'll need to look at the jQuery documentation.
Like Josh Beam said, you need to use either the $.get() function to do the work! So update your code like:
$(document).ready(function() {
setInterval(function() {
$.get('headlines.php', function (data) {
$('.headlines').html(data);
});
}, 10000);
});
The $.load() function will blink. So we can use any other AJAX function, probably, $.ajax() or $.get() and inside the success function, we can update the .html() of the .headlines.
I have a function that loads content using .load() (but it could use anything). Sometimes the content loads so fast that the transition animations I use don't look very good, in fact its quite off-putting. I would like to add a minimum time between the transitions so that if the content loads very quickly itll still wait the minimum time (say 500 ms).
My code currently looks like this, is there a nice jQuery way of doing this?
$("body").on("click","a[href]",function (e) {
e.preventDefault();
var href = $(this).attr("href");
// Do pre load animation (removed for clarity)
$("#rightpanel").load($(this).attr("href"), function () {
// Do post load animation (removed for clarity)
History.pushState(null, null, href);
});
});
Here is an answer involving promises :
// suggestion 1
// wait for both pre-load animation and load to complete :
$.when(
$('.gizmo').slideUp(),
$("#rightpanel").load($(this).attr("href"))
).done(function(){
$('.gizmo').stop().slideDown();
History.pushState(null, null, href);
});
// suggestion 2
// add a "500ms promise" :
function delay(time) {
var dfd = $.Deferred();
setTimeout(function(){ dfd.resolve() }, time);
return dfd.promise();
}
$.when( delay(500), $("#rightpanel").load($(this).attr("href")) ).done(function(){
//post load stuff
});
Here is a fiddle to play with.
As Chris correctly pointed out in the comments, the above code will not work with .load() : .load() applies to a jQuery selection, and returns the selected set instead of the underlying ajax promise.
The above code will work if you use $.ajax, $.get, $.post or other global jQuery functions,
or you can create an extra promise :
var loadData = $.Deferred();
$('#rightpanel').load($(this).attr('href'), function(){ loadData.resolve() });
$.when( delay(500), loadData ).done( ... )
I've done this a month before...
But now its not working...
The code is
window.onload = function(){
setTimeout(function(){
alert("Hello");
}, 10000);
};
This is written in script in head of the test.php page.
The script and other tags are correct.
I would like to call a specific function every 10 seconds. The alert just shows once only. This is problem in every browser....
After this testing i would like to check the url every 2 seconds and call an AJAX function.
Any Help??
That's what setTimeout does (executes once after a specified interval). You're looking for setInterval (calls a function repeatedly, with a fixed time delay between each call to that function):
window.onload = function(){
setInterval(function(){
alert("Hello");
}, 10000);
};
Use setInterval instead.
var fn = function(){alert("Hello")};
It is possible using setTimeout:
window.onload = function(){ setTimeout( function(){ fn();window.onload() },10000) };
but the best solution is setInterval:
window.onload = function() { setInterval(fn,10000)};
setTimeout is intended for one-time run. Look at setInterval function.