Here is a script I wrote so i could refresh a div with content every 5 seconds but for some reason it doesnt work ... I wanted it to load it with the page then start the refresh I didn't want it to have to wait for the refresh to show up.
<script type="text/javascript">
function page_load(){
$('#contentforads').load('<?php print $actual_link ?>/ads.php').fadeIn("slow");
}
function refresh(){
page_load();
var auto_refresh = setInterval(page_load,5000);
}
</script>
page_load() doesn't return a function, therefore you should pass it by reference to the interval rather than executing it.
var auto_refresh = setInterval(page_load,5000);
Don't forget to execute refresh to begin the interval.
function page_load(){
$('#contentforads').load('<?php print $actual_link ?>/ads.php').fadeIn("slow");
}
function refresh(){
page_load();
var auto_refresh = setInterval(page_load,5000);
}
refresh();
Change:
setInterval(page_load(),5000);
to:
setInterval(page_load,5000);
I'd change your code to this:
var a = function page_load(){
$('#contentforads').append(new Date());
}
setInterval(a, 5000); //every 5 seconds
Heres why I recommend:
Less code xD
Functions take up memory as they are considered variables in JS so this is more optimized
Note: Working fiddle
Related
This question already has answers here:
How to make JavaScript execute after page load?
(25 answers)
Closed 7 years ago.
I have a script which displays seconds before showing hiding the div.
var seconds_left = 20;
var interval = setInterval(function() {
document.getElementById('timer_div').innerHTML = "Or wait " + --seconds_left + " seconds to play the video.";
if (seconds_left <= 0)
{
//alert('The video is ready to play.');
$('#def').fadeOut('slow');
clearInterval(interval);
}
}, 1000);
The problem is.. even the page is not fully loaded, the counting automatically starts.
What can i do to make the counting start after the page fully loaded?
You shouldn't directly assign your onload, it will replace any existing onload. Onload is used frequently so overriding it is a bad idea. Do something like this:
window.addEventListener ?
window.addEventListener("load",yourFunction,false) :
window.attachEvent && window.attachEvent("onload",yourFunction);
If you can use a JS library like jQuery it will probably make things easier for you. You can use
$(document).ready(function() {
// your code
});
Ref: https://ckon.wordpress.com/2008/07/25/stop-using-windowonload-in-javascript/
you can set an 'onload' event on your body tag, which runs as soon as your content finishes loading:
<body onload='yourFunction()'>
Try calling it in the window.onload = function () { alert("It's loaded!") }
Example
window.onload = function () {
someFunction();
}
function someFunction() {
var seconds_left = 20;
var interval = setInterval(function () {
document.getElementById('timer_div').innerHTML = "Or wait " + --seconds_left + " seconds to play the video.";
if (seconds_left <= 0) {
//alert('The video is ready to play.');
$('#def').fadeOut('slow');
clearInterval(interval);
}
}, 1000);
}
Here is the best way if you really want to make sure your page is fully loaded:
$(function() {
// work when all HTML loaded except images and DOM is ready
});
$(window).load(function() {
// this is come when complete page is fully loaded, including all
// frames, objects and images **/
});
Use the load function for this problem I suggest you. Have a good day
If you use jQuery do like this:
$(function(){
//your code
});
And it's code will run after when page is loaded.
My Script :
function pagination(id)
{
$("#article_load_destacados").load("indexer_destacados_news.php?pg_d="+id);
if (id+1>2)
{
pagination(0);
setInterval(function()
{
pagination(0);
}, 4000);
}
else
{
setInterval(function()
{
pagination(id+1);
}, 4000);
}
}
</script>
<div id="article_load_destacados"></div>
<script>
pagination(0);
</script>
Create this script for show pagination, the script call PHP file and load this with pagination, for this send different ids and when load PHP file load the same time different elements of pagination. With this script I want run all pagination based on id. If I have for example 5 pages, the script run from 0 to 5, I use for setInterval for it with jQuery.
I want get the script paginate and send different id each 4 seconds.
The problem when run the script the navigator doesn't work, and generates an infinite loop.
As pointed out you want setTimeout not setInterval, you can also simplify your code http://jsfiddle.net/rayBt/
var imax = 3;
var time = 500;
function pagination(id){
$("#article_load_destacados").load("indexer_destacados_news.php?pg_d="+id);
id = (id + 1) % imax;
setTimeout(function () {
pagination(id);
}, time);
}
setInterval is used to have a function repeat at a given interval. Because you're calling setIntveral recursively, your script will be executing pagination with many different values once pagination starts.
You should use setTimeout instead. setTimeout starts a function after a given period of time, which sounds like what you want.
After loading the document, I want to refresh the page once. So I wrote this code. It is working fine, but it is calling again and again. because I am refreshing same page. but I want to clear the interval after one time execution.
function refreshPage(){
document.location.reload(true);
alert('page is refresh.');
}
var interval = setTimeout('refreshPage()', 3000);
If you want it to work only once, whatever the delay, you could store in localStorage the fact you did it :
function refreshPage(){
alert('page will refresh.');
document.location.reload(true);
localStorage['refreshDone'] = 'yes';
}
if (!localStorage['refreshDone']) {
setTimeout('refreshPage()', 3000);
}
But you can't simply clear the timeout or interval as the window variables are lost each time you reload the page.
As I'm not sure of your exact goal, in case you'd want to refresh if it hasn't been done recently, you could store a timestamp in localStorage :
function refreshPage(){
alert('page will refresh.');
document.location.reload(true);
localStorage['refresh'] = new Date().getTime();
}
var lastTimeRefresh = parseInt(localStorage['refresh']||'0', 10);
if (new Date().getTime() - lastTimeRefresh > 30*60*1000) { // 30 minutes
setTimeout('refreshPage()', 3000);
}
You could set javascript cookies at the first refresh and then check if cookies are set or not, If it is not set please set the cookies and refresh the page, If not do nothing
currently, I'm redirecting users after x seconds to another page, but what I want to do is, redirect users after y seconds and the timer will start only after user click a link on my page, currently the timer starts only after the user visit my page.
Here is the code I found doing google search -
<head>
<script>
function js_wait()
{
setTimeout (js_go(), 3000); // 3000 ms = 3 secs
}
function js_go()
{
window.location = "mynexpage.php";
}
</script>
</head>
<body>
My link
</body>
The body shows a link
On click, it calls the javascript function "js_wait"
js_wait starts a timer for x seconds, then calls js_go
js_go redirects to the page.
I was able to make it redirect onclick but it redirects immediately after clicking the link, but I want it to wait y seconds before redirecting.
Dont activate the method instead just pass the function signature like this:
<head>
<script>
function js_wait()
{
setTimeout (js_go, 3000); // 3000 ms = 3 secs
}
function js_go()
{
window.location = "mynexpage.php";
}
</script>
</head>
<body>
My link
</body>
Remove () from setTimeout function parameter.
setTimeout (js_go, 3000); // 3000 ms = 3 secs
If you have it there, it means you pass the result of the function call rather then the function reference.
As background information, setTimeout can be used in two different ways: either you pass it a function reference, like what you have done, or you pass a string, which will be evaluated by the time setTimeout fires. This means that if you want to pass some parameters to setTimeout, you'd either pass them as a string (like setTimeout('js_go("http://google.fi")', 3000)) or wrap them to a function, which is the preferred way (setTimeout(function() {js_go("http://google.fi")}, 3000)).
However, since you don't use parameters here, you should just pass the function reference like shown in the code block above.
Try this please much simpler: Working demo http://jsfiddle.net/FE4cT/
For redirect this is key: window.parent.location
Rest I hope it will fit your need :)
code
function js_wait() {
setTimeout(function() {
window.parent.location = "http://www.google.com";
}, 3000);
}
Sample
window.setTimeout(function() {
window.location.href = 'http://www.google.com';
}, 3000);
i.e. in your specific case:
window.setTimeout(function() {
window.location = 'mynexpage.php';
}, 3000);
Simply write as :
function js_wait_redirect() {
setTimeout(
function(){
window.location = "mynexpage.php";
}
, 3000); // 3000 ms = 3 secs
}
Im using javascript to include some content served up from a php file on another server. However, this other service can sometimes get flaky and either take a long time to load or will not load at all.
Is there a way in JS to try to get the external data for x number of seconds before failing and stopping to include js.
If you mean
<script src="javascript.php"></script>
then the short answer is no which is why JSONP is not useful in these cases.
The longer answer is that you might be able to use setTimeout and test a variable you KNOW should be in the javascript and give an error if the var/function is not there.
If you do
<script>
var start = new Date();
var tId;
function testFunction() {
var end = new Date();
if ( (end.getTime()-start.getTime()) > 10000) {
alert('gave up')
}
else if (someFunction) { // someFuntion in the external JS
someFunction()
}
else tId=setTimeout(testFunction,1000)
}
</script>
<script src="javascript.php"></script>
<script type="text/javascript">
var jsLoaded = false;
setTimeout("callback()", 2000);
function callback() {
if (!jsLoaded) {
alert("Javascript not loaded after 2 seconds!");
} else {
alert('Loaded');
}
}
</script>
<script type="text/javascript" id="foo" src="url.js" onload="jsLoaded=true"></script>
Now, good luck to find what to do in order to stop loading the script.. I've tried to remove the <script> element from the DOM but it's still try to load...
If you .js is hosted on the same domain, I suggest you to use AJAX method to load the javascript (see http://codesnippets.joyent.com/posts/show/602)