I'm trying to load three different html files into a div, one after the other, with a delay of 5 seconds. After it cycles through all three I want it to carry on repeating. I tried using timeout to do this but its still not working.Any help would be appreciated.. code snippet below
<script type="text/javascript">
$(document).ready(function() {
jQuery(window).load (function timeout() {
setTimeout(function () {
if($("#news_sections").hasClass("news1")){
$("#news_sections").attr('class', "news2");
$( "#news_sections" ).load( "section2.html" );
}else if($("#news_sections").hasClass("news2")){
$("#news_sections").attr('class', 'news3');
$( "#news_sections" ).load( "section3.html" );
}else{
$("#news_sections").attr('class', 'news1');
$( "#news_sections" ).load( "section1.html" );
};
timeout();
}, 4000);
});
});
});
</script>
Untested but you should do something like this:
$(function(){
var curIdx = 0, /* internal counter */
urls = ['page1.html','page2.html','page3.html'], /* your urls*/
doCache = true, /* set to false to disable caching */
cache = {} /* storage */;
function nextPage(){
var data = false,
url = urls[curIdx];
if(doCache && cache[url]) {
data = cache[url];
}
curIdx += 1;
// all urls displayed - reset counter, show first page again
if(curIdx == urls.length) {
curIdx = 0;
}
// load data (and cache it, if doCached option is true)
if(!data){
$("#content").load(url, function(data){
cache[url] = data;
nextTimer();
})
} else {
$("#content").html(data);
nextTimer();
}
};
// now to timeout
function nextTimer(){
window.setTimeout(function(){ nextPage() }, 5000); // 5 Seconds
}
// and run it...
nextPage();
});
Be aware that this might not work with external urls.
You can use this, instead of changing classes and depending on them.
In case you have more than 10 sectionX.html files, you will need to write a lot of code there. So if you make an counter, you have to change only the if statement to (count > X) where X = number of templates you have.
var count = 1;
setInterval(function () {
// If the count is more 3, we reset the count to 1.
if (count > 3) {
count = 1;
}
// If you are using "newsX" class for looping propose only,
// You can remove .attr() method in my solution.
$("#news_sections").attr('class', "news" + count);
// clear news section
$("#news_sections").empty();
// Load the count number sectionX.html file
// Also increase count number with 1 (count++)
$("#news_sections").load( "section" + count++ + ".html" );
}, 1500);
Your code seems a bit convoluted, and you should probably not use setTimeout like that. I believe what you're looking for is setInterval, which executes the same function repeatedly, every X milliseconds.
I simplified it a bit. First, declare the loopNews() function, and then set the timeout call when the document is ready.
function loopNews(){
if($("#news_sections").hasClass("news1")){
$("#news_sections").attr('class', "news2");
$("#news_sections").load( "section2.html" );
}else if($("#news_sections").hasClass("news2")){
$("#news_sections").attr('class', 'news3');
$("#news_sections").load( "section3.html" );
}else{
$("#news_sections").attr('class', 'news1');
$("#news_sections").load( "section1.html" );
}
}
$(document).ready(function() {
window.setInterval(loopNews, 5000);
});
Related
i don't really know how to create time loop for this JS function..
Here is that function: enter link description here
Just what i need is a time loop every 20 seconds for a random sort..
I used - var ... = setInterval(..., 20000);
And - var ... = setTimeOut(...,20000);
But i don't know where to connect or if someone know better way how to do that everything gonna help me with that..
Thanks a lot for any help..
You have several issues with your attempt, the below will do what you want, just adjust the timer as needed
Updated CodePen
function loop() { // you had $(function loop(){... here, that is not right
$container = $('#Container');
if ($container.mixItUp('isLoaded')) { // check if the plugin has been initialized
$container.mixItUp('sort', 'random', true); // if loaded, just resort
// change true to false, to forego the animation
} else {
// if not initialized, do that now
$container.mixItUp({
load: {
sort: 'random'
},
layout: {
containerClass: 'list',
display: 'block'
}
});
}
}
$(function() { // here you had a for loop, not sure why but the int should have been var, anyway, I removed it altogether
setInterval(loop, 2000);
});
Try this:
http://codepen.io/anon/pen/BoZvEx
$(document).ready(function () {
var mixit = $('#Container').mixItUp({
load: {
sort: 'random'
},
layout: {
containerClass: 'list',
display: 'block'
}
});
function loop() {
mixit.mixItUp('sort', 'random');
};
var looper = setInterval(loop, 1000);
});
In there, the code is inside a $(document).ready, and there first we instantiate once, with the config in the parameter, and then the method loop does exactly just one call to sort.
$(document).ready(function(){
setTimeout(function(){
for( var i = 0; i < 10; ++i )
{
loop();
}
},20000);
});
I think you need this
i have one nested casper.repeat in casper.repeat loop. and i need escape from inner and continue from first casper.start().repeat(500... when one element appears.. i scrape site where i pass pages and in one of this pages(i dont know exactly which one) one element can appear and i need to to break this loop and continue from start point.
well this is my code:
casper.start().repeat(500, function() {
if(counter==11) {
page_counter++;
counter=0;
}
casper.open('http://my.ya.ru/clubs_rating.xml?p=' + page_counter);
var links = this.getElementsInfo('dl.info dt a');
this.echo('Opened page: ' + this.getCurrentUrl());
casper.repeat(40, function() {
//here i need make **waitFor** to check element every time////////
//and if it's here - break loop and go to start point/////////////
if(innercounter==19) {
ipagecounter=ipagecounter+20;
innercounter=0;
}
Try:
casper.waitForSelector('#your_selector_id', function() {
test.assertExists('#your_selector_id', "We've find this element\^_^/!");
}, function () {
this.echo('Wasn't found in 10 seconds!');
}, 10000);
Or look at https://github.com/yotsumoto/casperjs-goto
Goto is a peace of sadness, but I believe might be useful.
casper.start();
casper.repeat(500, function() {
casper.open('http://my.ya.ru/clubs_rating.xml?p=' + page_counter);
casper.label( "LABER_FOR_BREAK" );
var counter=0;
casper.label( "LOOP_START" );
casper.then(function(){
//check selector
if( /*true selector assertion*/ ){
this.goto( "LABEL_FOR_BREAK" );
};
});
casper.then(function() {
counter++;
this.echo( counter );
});
casper.then(function() {
if( counter<41 ){ this.goto( "LOOP_START" ); }
});
});
casper.run( function() {
this.dumpSteps( true );
this.exit();
});
Does this make sense?
When the tab my website is on is inactive, my slideshow starts switching pictures too fast and mess the whole thing up.
Is there a way i could fix this?
var img_src = ["1.png", "2.png", "3.png", "4.png"];
var delay = 8000;
var first_run = true;
function switch_pic(position){
$("#show").attr("src", img_src[position]).fadeOut(0).fadeIn(4000).fadeOut(4000);
}
$(document).ready(function(){
var i = 0;
if(first_run){
switch_pic(i);
first_run = false;
i++;
}
window.setInterval(function(){
switch_pic(i);
delay += 8000;
i++;
if(i > 3){
i = 0;
window.clearInterval();
}
}, delay);
});
Could wrap the code in this:
$(document).ready(function(){
$([window, document]).focusin(function(){
//code run when tab is selected
}).focusin(function(){
//code to stop all animation
});
});
That would only let the slideshow run when the user is viewing your site.
I'm not sure why things speed up. Normally the timers on background tabs will be slowed down to at least one second, but this shouldn't affect your scenario. I suggest using console.log() to track the calls to your functions.
Also, you can simplify your main loop a bit:
$(document).ready(function(){
var i = 0;
window.setInterval(function(){
switch_pic(i++); // increase i after call
if(i > 3) i = 0; // reset i
}, 8000);
});
I think that the answer good for actual version of jQuery should look like this:
var intervalId;
$([window, document]).on('focusin', function(){
intervalId = setInterval(function() {
// Action in interval
}, 3000);
}).on('focusout', function(){
if (intervalId) {
clearInterval(intervalId);
}
});
Pleas remember, that first time your 'focusin' is not tigger when page is loaded, so you should use this construction for this:
intervalFunction();
$([window, document]).on('focusin', function(){
if (!intervalId){
intervalFunction();
}
}).on('focusout', function(){
if (intervalId) {
clearInterval(intervalId);
intervalId = undefined;
}
});
function intervalFunction() {
// Your function hire
}
what I got now is:
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
But I want this interval to pause if the mouse cursor is placed inside a div on my website. How do I attack this problem? Surely I need to give the div an ID.. But some input on how to make the javascript/jquery part is much appreciated.
EDIT: More of my code.. I'm not quite sure where to insert the code in the answers inside this:
$(
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
TwitterCache = {};
function getSearch()
{
var url = "http://search.twitter.com/search.json?q=test&refresh=6000&callback=?"; // Change your query here
$.getJSON
(
url,
function(data)
{
if( data.results ) // Checks to see if you have any new tweets
{
var i = -1, result, HTML='', HTML2='';
while( (result = data.results[++i]) && !TwitterCache[result.id] )
{
insert html.. blabla}
setInterval returns a "reference" to that interval you set up, allowing you to stop it with window.clearInterval(), and that's what you have to do:
var myInterval;
function startMyInterval() {
if (!myInterval) {
// It's better to call setInterval width a function reference, than a string,
// also always use "window", in case you are not in its scope.
myInterval = window.setInterval(getSearch, 10000);
}
}
function stopMyInterval() {
if (myInterval) {
window.clearInterval(myInterval);
}
}
startMyInterval(); // Start the interval
jQuery("#myDiv").hover(stopMyInterval, startMyInterval);
Set a global variable
var intID;
Assign setInterval to this variable
intID = setInterval("getSearch()",10000);
Set an id for the div
$("#divid").hover(function(){
clearInterval(intID);
},
function(){
// set the interval again
});
I think this should work:
$("#divID").hover(
function () {
PauseTheInterValThing()
},
function()
{
setInterval("getSearch()",10000);
getSearch();
}
);
The simplest way, and the shortest
Simplest method would be:
<div id="yourDiv">
EXAMPLE TEXT
</div>
<script language="Javascript">
var interval = setInterval("getSearch()",1000);
document.getElementById("yourDiv").addEventListener('mouseover', function()
{
clearInterval(interval);
},false);
document.getElementById("yourDiv").addEventListener('mouseout', function()
{
interval = setInterval("getSearch()",1000);
},false);
</script>
insert this in your dom-ready function:
var inv = setInterval("getSearch",1000);
$('#yourdiv').mouseover(function(){
clearInterval(inv);
}).mouseout(function(){
inv = setInterval("getSearch",1000);
})
I have what i thought was a simple javascript / jquery function (fade out of one div, fade into another... loop until it reaches a maximum and then start back from the begining. The problem i have though is that to fadein the next div i need to increment the global counter. Doing this increments double increments it because i'm assuming the local variable i've created maintains the same reference to the global variable.
The code sample below should explain a little easier. Can anyone spot what i'm doing wrong?
var current_index = 1;
$(document).ready(function() {
$(function() {
setInterval("selectNextStep()", 3000);
});
});
function selectNextStep() {
$("#step_"+current_index).fadeOut('slow', function() {
var next = current_index;
next = next + 1;
$("#step_"+next).fadeIn('slow', function() {
if (current_index == 4) current_index = 1;
else current_index ++;
});
});
}
I think you're ending up with race conditions due to the interval trying to fade things in and the callbacks trying to fade things out. For this setup it makes more sense to let the fade callbacks start the next round.
Also using a 0-based index makes the math easier.
var current_index = 0; // zero indexes makes math easier
$(document).ready(function () {
$(function () {
// use timeout instead of interval, the fading callbacks will
// keep the process going
setTimeout(selectNextStep, 3000);
});
});
function selectNextStep() {
// +1 to adapt index to element id
$("#step_" + (current_index + 1)).fadeOut('slow', function () {
var next = current_index + 1;
// keeps index in range of 0-3
next = next % 4; // assuming you have 4 elements?
current_index = (current_index + 1) % 4;
// callback will start the next iteration
$("#step_" + (next + 1)).fadeIn('slow', function () {
setTimeout(selectNextStep, 3000);
});
});
}
demo: http://jsbin.com/exufu
I do not see any double increment the way your code is..
the problem is that the next variable goes beyond the 4 value that seems to be the limit, and trying to fadein an element that does not exist. so the code that resets the currentIndex never executes..
try adding if (next > 4 ) next = 1; after increasing the next variable
Example at http://jsfiddle.net/5zeUF/
isn't $(function() {}); the same as $(document).ready(function(){}), so you are initializing selectNextStep twice (hence the double increment)?
Try this. Simplifies things a little. Increments (and resets if needed) the current_index before the next fadeIn().
Example: http://jsfiddle.net/r7BFR/
var current_index = 1;
function selectNextStep() {
$("#step_" + current_index).fadeOut('slow', function() {
current_index++;
if (current_index > 4) current_index = 1;
$("#step_" + current_index).fadeIn('slow');
});
}
$(document).ready(function() {
setInterval(selectNextStep, 3000);
});
EDIT: Added example, and fixed my misspelling (camelCase) of current_index.
Here's an alternate way of doing the increment:
current_index = (current_index % 4) + 1;
Try this, slightly different approach but does what you need it to do I believe, also you can add more steps without modifying the script and doesn't pollute the global namespace (window)
[HTML]
<div class="step defaultStep">One</div>
<div class="step">Two</div>
<div class="step">Three</div>
<div class="step">Four</div>
<div class="step">Five</div>
[CSS]
.step { display: none; }
.defaultStep { display: block; }
[JS]
$( function() {
var steps = $( ".step" );
var interval = setInterval( function( ) {
var current = $( ".step" ).filter( ":visible" ), next;
if( current.next( ).length !== 0 ) {
next = current.next( );
} else {
next = steps.eq(0);
}
current.fadeOut( "slow", function( ) {
next.fadeIn( "slow" );
} );
}, 3000);
} );
Maybe you also want to have a look at the cycle plugin for jquery. There you can actually achieve such nice transitions. I think with a little work this would ease up everything.
http://jquery.malsup.com/cycle/
Regarding your code snippet. I think you can enhance it a little in this way:
$(document).ready(function() {
var current_index = 0;
window.setInterval(function() {
$("#step_"+ current_index).fadeOut('slow', function() {
$("#step_" + (current_index + 1)).fadeIn('slow', function() {
current_index = (current_index + 1) % 4;
});
});
}, 3000);
});
This should do the exact same work. As the interval function closes over the current_index variable it should be valid inside the function. Sorry, if you're not a fan of all these closures but I rather preferr passing the function I want to execute directly to the setInterval function, than defining it anywhere else.
P.S. Be aware that the changes I introduced imply that your #step_ IDs start at 0.