jQuery setInterval too fast when tab is inactive - javascript

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
}

Related

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!

Count how many seconds did the user hover an element using jquery or javascript?

just need a little help here. My problem is, how can I count the seconds when i hover a specific element. Like for example when I hover a button, how can i count the seconds did i stayed in that button after I mouseout?
An alternate solution using setInterval. DEMO HERE
var counter = 0;
var myInterval =null;
$(document).ready(function(){
$("div").hover(function(e){
counter = 0;
myInterval = setInterval(function () {
++counter;
}, 1000);
},function(e){
clearInterval(myInterval);
alert(counter);
});
});
A simple example
var timer;
// Bind the mouseover and mouseleave events
$('button').on({
mouseover: function() {
// set the variable to the current time
timer = Date.now();
},
mouseleave: function() {
// get the difference
timer = Date.now() - timer;
console.log( parseFloat(timer/1000) + " seconds");
timer = null;
}
});
Check Fiddle
How about this quick plugin I just knocked out, which will work on multiple elements, and without using any global variables:
(function($) {
$.fn.hoverTimer = function() {
return this.on({
'mouseenter.timer': function(ev) {
$(this).data('enter', ev.timeStamp);
},
'mouseleave.timer': function(ev) {
var enter = $(this).data('enter');
if (enter) {
console.log(this, ev.timeStamp - enter);
}
}
});
};
})(jQuery);
Actually disabling the functionality is left as an exercise for the reader ;-)
Demo at http://jsfiddle.net/alnitak/r9XkX/
IMHO, anything using a timer for this is a poor implementation. It's perfectly trivial to record the time without needing to use an (inaccurate) timer event to "count" seconds. Heck, the event object even has the current time in it, as used above.
This is exam:
var begin = 0;
var end = 0;
$('#btn').hover(function () {
begin = new Date().getTime();
});
$('#btn').leave(function () {
end = new Date().getTime();
sec = (end - begin) / 1000;
alert(sec);
});
One way to go about it would be the event.timeStamp method :
var initial_hover, exit_hover;
$('#ele').hover(
function(event){
initial_hover = event.timeStamp
console.log(initial_hover);
},
function(event){
exit_hover = event.timeStamp
$(this).html(exit_hover - initial_hover);
console.log(exit_hover);
}
);
jsfiddle
You've tagged the question with JQuery, so here's a jQuery solution.
$(element).on('mouseover', function(e){
$(e.target).data('hover-start', new Date().getTime());
});
$(element).on('mouseout', function(e){
// count the difference
var difference = new Date().getTime() - $(e.target).data('hover-start');
// clean up the data
$(e.target).data('hover-start', undefined);
console.log('Mouse was over for', difference/1000, 'seconds');
});
use setInterval and store value in variable. call the function on mouserover.
function mouseover(){
var start = 0;
setInterval(function(){
start++;
var count = start;
}, 1000);
}

How to make this a slow jQuery counter

I am currently busy with making a new website.
I would like to make a counter on my website that shows visitors how many websites I made.
I am currently using Javascript and jQuery to do this. The only problem is that while using the for loop, the result shows very fast and I would like it to count up slowly. This is the code I have so far:
$(document).ready(function() {
var websites = 10;
for (var i=0;i<websites;i++)
{
$('.webcounter').html(i);
}
});
Any one has an idea to making the counter go slow?
You can try this:
var interval = window.setInterval(func, delay[, param1, param2, ...]);
This timer works in seconds, you can put the code to run after it's complete in the else section:
Javascript
function countdown(count){
$('.webcounter').html(count);
count -= 1;
if(count >= 0)
setTimeout("countdown("+count+")", 1000);
else
alert("Countdown Complete");
}
$(document).ready(function() {
countdown(10);
}
HTML
<div class="webcounter">Webcounter Holder</div>​
Demo
http://jsfiddle.net/silver89/SBXAQ/8/
Use setInterval:
EXAMPLE
HTML
​<div class="websites">0</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​
JQUERY
$(document).ready(function() {
var websites = 10;
var counter = 1;
var id = setInterval(function(){
$('.websites').text(counter);
counter++;
if(counter > websites){ clearInterval(id);}
}, 500);
});​
Just a quick guess, but try something like this (i'm at work and cant test myself, heheh)
var websites = 10, tmrSiteCount;
function siteCount(i) {
if (i <= websites) {
$('.webcounter').html(i);
tmrSiteCount = setTimeout(function() { siteCount(i++); }, 1000);
}
else {
clearTimeout(tmrSiteCount);
};
}
$(document).ready(function() {
tmrSiteCount = setTimeout(function() { siteCount(1); });
})

Reset slide interval JQuery

I've made a slide show width a javascript and Jquery. But I need to reset the slide interval when the user is navigating manualy to the next or previous slide. I am relatively new to javascipt and it's syntax. Any help will be appriciated. Here is my code:
<script type="text/javascript" src="/elements/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var currentSlideId = 0;
var slidesAmount = 0;
function selectSlide(id) {
jQuery(".startpage-test.slide" + id).show().siblings(".startpage-test").hide();
jQuery(".slideshow-show-active.slide" + id).addClass("active").siblings(".slideshow-show-active").removeClass("active");
}
function nextSlide() {
currentSlideId++;
if (currentSlideId >= slidesAmount) currentSlideId = 0;
selectSlide(currentSlideId);
}
function prevSlide() {
currentSlideId--;
if (currentSlideId < 0) currentSlideId = slidesAmount - 1;
selectSlide(currentSlideId);
}
jQuery(document).ready(function() {
slidesAmount = jQuery(".startpage-test").length;
jQuery(".show_previous").click(function() {
prevSlide();
return false;
});
jQuery(".show_next").click(function() {
nextSlide();
return false;
});
window.setInterval(function() {
nextSlide();
}, 7000);
});
jQuery("object.flashContent").each(function () {
swfobject.registerObject(jQuery(this).attr("id"), "9.0.0");
});
</script>
The next-/prev-button looks like this:
<div class="show_next">
<span class="slide_nav"><img src="/elements/next.png" width="57" alt="Next"></span>
</div>
<div class="show_previous">
<span class="slide_nav"><img src="/elements/prev.png" width="57" alt="Previous"></span>
</div>
In all slides there is a link of course, and it would also be nice to stop the slide interval when hovering this a-tag. Unfortunately I don't know how to do this either.
You can assign the result of setInterval() to a variable, then call clearInterval() passing in that variable whenever you need. So in your case, change this code:
window.setInterval(function() {
nextSlide();
},
to this:
var interval = window.setInterval(function() {
nextSlide();
},
Then, in any.hover(), .mouseenter(), .click() or whatever other mouse event handler you are using, simply call:
window.clearInterval(interval);
Of course, you need to reinstate the interval when you want to restart it!

Hide download link for 10 seconds? js

hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks
Complete example:
<span id="countdown"></span>
<a id="download_link" href="download.zip" style="display:none;">Download</a>
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript>
<script type="application/javascript">
(function(){
var message = "%d seconds before download link appears";
// seconds before download link becomes visible
var count = 10;
var countdown_element = document.getElementById("countdown");
var download_link = document.getElementById("download_link");
var timer = setInterval(function(){
// if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed
if (count) {
// display text
countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count);
// decrease counter
count--;
} else {
// stop timer
clearInterval(timer);
// hide countdown
countdown_element.style.display = "none";
// show download link
download_link.style.display = "";
}
}, 1000);
})();
</script>
You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();
var iteration = 0;
var timer = setInterval(function() {
if(iteration++ >= 10) {
clearTimeout(timer);
$(".link").show();
$(".counter").hide();
}
$(".counter").text(10 - iteration);
}, 1000);
This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.
Take a look at the setTimeout function. You can do something like:
function displayLink() {
document.getElementById('link_id').style.display = 'block';
}
setTimeout(displayLink, 10000);
var WAIT_FOR_SECONDS = 10;
var DOWNLOAD_BUTTON_ID = "btnDownload";
if (document.body.addEventListener) {
document.body.addEventListener("load", displayDownloadButton, false);
} else {
document.body.onload = displayDownloadButton;
}
function displayDownloadButton(event) {
setTimeout(function() {
_e(DOWNLOAD_BUTTON_ID).style.display = "";
}, WAIT_FOR_SECONDS*1000);
}
function _e(id) {
return document.getElementById(id);
}

Categories

Resources