Javascript setTimeout call multiple time - javascript

I have a one page horizontal sliding site. each slider has a question and a timer. when user slides to next, it should reset the timer and start from beginning. here is my jquery code:
$(document).ready(function(){
var mytimer;
$('#main').on('click', '.slidinglink', function(e){
e.preventDefault();
var section = $(this).attr('href');
var slide = $(this).data('slide');
var left = '';
if(section != '#'){
$('.timer').show();
left = '-100%';
var $active_question = $('.answer-list.active');
//mytimer = null;
clearTimeout( mytimer );
mytimer = setTimeout(function () {
finish_question( $('.answer-list > li.checked') );
}, 5000);
do_sliding(left, section, slideback);
}
});
});
The timer works for the first time. but if i go to next section, the timer does not work. What seems to be the problem? I have 2 other setTimeout functions which are also called during slide. They are like this (both similar):
setTimeout(function(){
item.removeClass('clone');
}, 20);

Related

How to add a timer onto a page scroll

I'm working on building an infinite page-scroll, at least until it reaches the last page. However, it scrolls way to quickly and overloads my web-browser. I wanted to know how I can implement a time-lag on each scroll, something like 1-2 seconds between the scrolls.
Here's what I have developed so far:
var infScroll = setInterval(function () {
var scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
}, 200);
It works and keeps scrolling down the page, however, how do I set a lag between each scroll?
I have tried updating it with a timer as the following:
function disableScroll() {
// temporarily disable action
scrollEnabled = false;
// set a timer to enable again it 1 second from now
setTimeout(function() {
scrollEnabled = true;
}, 8000);
}
var infScroll = setInterval(function () {
var scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight; disableScroll()
}, 200);
However, the function won't stop the scroll at all for a few moments.

Jquery, Click to kill a function

I'm trying to create a slider with three slides. Originally, the slides will display as a loop. My goal is, if a button like #fancy_1 is clicked, the loop with a function name "runem" will be stopped and the loop just ends there. I tried put a stop(true,true), but with no success. No matter whether the button is clicked or not, the loop is always running. Does anyone have any idea how to achieve this?
(function($) {
$(document).ready(function() {
function runem() {
var allofEm = $('.j_fancy .j_fancy_block');
var $active = allofEm.eq(0);
$active.show();
var $next = $active.next();
var timer = setInterval(function() {
$next.fadeIn();
$active.hide();
$active = $next;
$next = (allofEm.last().index() == allofEm.index($active)) ?
$next = allofEm.eq(0) : $active.next();
}, 5000);
}
runem();
$("#fancy_1").click(function() {
$('.j_fancy_block').eq(0).show();
$('.j_fancy_block').eq(1).hide();
$('.j_fancy_block').eq(2).hide();
runem().stop(true, true); //this doesn't work.
})
$("#fancy_2").click(function() {
$('.j_fancy_block').eq(0).hide();
$('.j_fancy_block').eq(1).show();
$('.j_fancy_block').eq(2).hide();
runem().stop(true, true); //this doesn't work.
})
$("#fancy_3").click(function() {
$('.j_fancy_block').eq(0).hide();
$('.j_fancy_block').eq(1).hide();
$('.j_fancy_block').eq(2).show();
runem().stop(true, true); //this doesn't work.
})
})
}(jQuery));
Have you tried using clearInterval()? The reason that stop() was not working is because that is a function to stop jQuery animations, not Javascript setInterval - so setInterval will continue to run
The way I would suggest using it is like so...
var boxInterval;
function runem(){
/*Function Stuff*/
boxInterval = setInterval(function(){...});
}
function stopBox(){
clearInterval(boxInterval);
}
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval#Example

How to pause and resume jquery interval

I have made a custom slider with jQuery. For this I have used setInterval function:
timer = setInterval(function() {}, 8000);
But I cannot pause and resume the interval. I have 2 buttons (play, pause) which I want to use for. Lets say I click pause after 3 sec, and then resume it. So it should stay in that slider for 5 more seconds and then go to the next one and continue 8 seconds each. I have seen this kinda slider with mouseover pause, but can't do it by myself. I have tried this:
clearInterval(timer);
But this seems reset the interval, don't pause. Can anyone help :)
I'm not entirely sure that's something native to jQuery, however, you could use a flag to pause it, and check in your setInterval whether to execute.
Edit:
Found something that might be useful to you, the jquery-timer
Alternitively, you can keep track of the id set by setInterval, and clear out out when you'd like to pause. Then you can set it again when you wish to resume:
var id = window.setInterval(<code>); //create
window.clearInterval(id); //pause
id = window.setInterval(<code>); //resume
there are two ways of accomplish this:
Clearing the interval everytime you pause and starting a new interval when you resume it.
Having a flag to tell the function in the interval when it is paused and it should not do anything.
The first solution would work like this:
let intervalId = false;
const intervalLength = 8000; // 8 seconds
function intervalFunction () {
// do stuff.
}
startButton.onclick = function () {
if (intervalId === false) {
intervalId = setInterval(intervalFunction, intervalLength);
}
}
pauseButton.onclick = function () {
if (intervalId !== false) {
clearInterval(intervalId);
intervalId = false;
}
}
// auto start it:
intervalId = setInterval(intervalFunction, intervalLength);
The second solution would work like this:
var isRunning = true;
var interval = setInterval(function() {
if (!isRunning) {
// not running, do nothing
} else {
// it is running, do stuff.
}
}, 8000);
pauseButton.onclick = function () {
isRunning = false;
};
startButton.onclick = function () {
isRunning = true;
};
I am not complete sure, that what you are asking for, is the right thing you are showing us... setInterval basically is pure native javascript and in my opinion not worth using! If you wan't to set your timeouts via jquery try this link: http://jchavannes.com/jquery-timer. You can find usages there...
Now on to your problem... you need a state to check wether the slider has to slide or not... simply set a bool like this...
var timer;
var doSlide = false;
var i = 0;
function Slide(){
timer = setTimeout(function(){
if(doSlide == true){
Slide();
i++; // Same as i = i + 1
console.log('Sliding');
if(i == 3) AbortSlide(); /* Abort on third slide! Dont use this in your logic!*/
} else if(doSlide == false){
console.log('Sliding aborted untill next RunSlide() call!')
clearTimeout(timer);
}
},1000);
}
function AbortSlide(){
doSlide = false;
i = 0; // Resetting the count! Dont use this in your logic!
}
function RunSlide(){
doSlide = true;
Slide();
}
RunSlide();
You could also empty the interval in the abort method:
function AbortSlide(){
doSlide = false;
clearTimeout(timer);
i = 0; // Resetting the count! Dont use this in your logic!
}
Here is a working fiddle i made for you to understand what timers and intervals are for: https://jsfiddle.net/q5qzmv68/7/
Hope this helps! Cheers!

Javascript Text Slideshow Start from Beginning on Hover

I have added a text slideshow to a div that is called by JQuery on hover. How do I get the slideshow to start from the beginning each time the user hovers on the div? Right now it just continues to loop after the first time it is activated.
Thanks in advance!
<script>
$(document).ready(function(){
$('#mercury .infos').hover(
function () {
if($("a.active").is('.mercury')){
$("#descriptionls").fadeIn("2000");
};
var quotes = [
"Who’s the one who’s always there when that keeps happening?",
"Learn to dismantle self-defeating behaviors",
"JOIN THE FLOW TODAY",
];
var i = 0;
setInterval(function() {
$("#lstextslide").html(quotes[i]);
if (i == quotes.length)
i=0;
else
i++;
}, 1 * 4000);
});
});
</script>
You have to cancel the previous interval and call the function that updates the HTML immediately. See http://jsfiddle.net/xozL96fj/
$(document).ready(function(){
var intervalTimer = null;
$('#mercury .infos').hover(
function () {
if($("a.active").is('.mercury')){
$("#descriptionls").fadeIn("2000");
}
if (intervalTimer !== null) {
clearInterval(intervalTimer);
}
var quotes = [
"Who’s the one who’s always there when that keeps happening?",
"Learn to dismantle self-defeating behaviors",
"JOIN THE FLOW TODAY",
];
var i = 0;
function update() {
$("#lstextslide").html(quotes[i]);
i = (i + 1) % quotes.length;
}
// Call it immediately, don't wait until the interval
update();
intervalTimer = setInterval(update, 4000);
});
});
You need to make a check if your slider has already been activated. If you hover over your slider when the slider is already active, you will have to reset $i, and call setInterval() again.

jQuery setInterval too fast when tab is inactive

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
}

Categories

Resources