jQuery + setTimeout() + clearTimeout() not working in IE7 & 8 - javascript

This works in Firefox and Chrome but not in IE.
In Internet Explorer the timers are not being cleared out and it appears each time update_slideshow() is called a new timer is created.
// slideshow params
var currentSlide = 1;
var numSlides = 4;
var pause = false;
function pause_show(bool){
pause = bool;
}
// transitions the slides
function update_slideshow(slide){
if(slide > numSlides) slide = 1;
//is user tyring to pause/play this slide
if(currentSlide == slide){
switch(pause){
case false:
$("#ssbut" + slide.toString()).removeClass('pause').addClass('play');
pause = true;
break;
case true:
$("#ssbut" + slide.toString()).removeClass('play').addClass('pause');
pause = false;
break;
}
}else{ //user clicked on a button other than the current slide's
clearTimeout(slideTimer);
function complete() {
$("#slide" + slide.toString()).fadeIn(500, "linear");
if(!pause)
$("#ssbut" + slide.toString()).removeClass('inactive').addClass('pause');
else
$("#ssbut" + slide.toString()).removeClass('inactive').addClass('play');
}
$("#ssbut" + currentSlide.toString()).removeClass('play').addClass('inactive');
$("#slide" + currentSlide.toString()).fadeOut(300, "linear", complete);
currentSlide = slide;
if (typeof(slideTimer) != 'undefined') clearTimeout(slideTimer);
slideTimer = setTimeout("slideshow()",4000);
}
}
function slideshow(){
if (typeof(slideTimer) != 'undefined') clearTimeout(slideTimer);
if(!pause){
update_slideshow(currentSlide + 1);
}
slideTimer = setTimeout("slideshow()",4000);
}
var slideTimer = setTimeout("slideshow()",4000);

You might try using setTimeout with a function reference instead of a string. Change this:
setTimeout("slideshow()",4000);
To this:
setTimeout( slideshow, 4000 );
As a side note, you might consider simplifying some code. You only have two states for pause, so this:
switch(pause){
case false:
$("#ssbut" + slide.toString()).removeClass('pause').addClass('play');
pause = true;
break;
case true:
$("#ssbut" + slide.toString()).removeClass('play').addClass('pause');
pause = false;
break;
}
...can be rewritten something like this:
$('#ssbut' + slide.toString()).toggleClass('pause play', pause);
pause = !pause;
Update: Noticed that the OP was inadvertently recursing in the slideShow function:
function slideshow(){
// stuff
slideTimer = setTimeout("slideshow()",4000); // -> now there's your problem
}
Removing that line solves the problem.

Related

Starting/Pausing canvas animation with a button click

I am trying to get a simple snake game running where the game is off default and you click Start to begin.
the StartStop button's code:
StartStop.onclick = function()
{
//flip the name on the button
if (StartStop.value = "Start")
{
StartStop.value = "Stop";
update();
}
else
{
StartStop.value = "Start";
clearInterval(update);
}
}
code inside update() starts the animation:
function update()
{
setInterval(function()
{
console.log(snake.x + ", " + snake.y);
//check for collisions
//if no collisions move and draw snake
snake.x += velocity[vi][0];
snake.y += velocity[vi][1];
snake.draw();
},30);
}
My thought process was when the button's text value is Start, it changes the text to Stop and calls update() which calls setInterval().
Then when you click the button and the text value is Stop, it calls clearInterval(timer) to stop the animation
I think I am not using setInterval correctly, any ideas on how to get it to start and stop on a button click?
I fixed it by changing my code to this:
StartStop.onclick = function()
{
if (StartStop.value == "Start")
{
StartStop.value = "Stop";
var timer = setInterval(
function()
{
if (StartStop.value == "Stop")
{
console.log(snake.x + ", " + snake.y);
//check for collisions
//if no collisions move and draw snake
snake.x += velocity[vi][0];
snake.y += velocity[vi][1];
snake.draw();
}
else
{
clearInterval(timer);
}
},30);
}
else
StartStop.value = "Start";
}

angular 4 setinterval pausing when switch tab

My setInterval timer is pausing when leave the tab and resume when switch back to the tab I want solution to make it keep counting when the tab is switched back
here is GIF picture shows what happen
here is my code:
startCountDown(time) {
clearInterval(this.countDownInterval);
this.timeLeft = time * 100;
if (time === 0) {
return;
}
this.countDownInterval = setInterval(() => {
this.timeLeft -= 1;
if (this.timeLeft === 0) {
clearInterval(this.countDownInterval);
}
}, 10);
}
updateTimer() {
if (this.timeLeft > 0) {
$('.rolling').fadeIn(200);
$('.rolling-inner').html('<div>' + (this.timeLeft / 100).toFixed(2).replace('.', ':') + '</div>');
} else {
$('.rolling').fadeOut(200);
}
}
set timeLeft(x) {
this._timeLeft = x;
this.updateTimer();
}
get timeLeft() {
return this._timeLeft;
}
Setinterval is not misbehaving , This is what it's property . But you can track the tab selection action and add the pending idle duration with existing time.
This is the code to track the tab selection and blur
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) {
switch (e.type) {
case "blur": break;
case "focus": break;
}
}
$(this).data("prevType", e.type);
})

Showing different pictures within 0.08 seconds timeout

I have this code which is supposed to show 24 images within a 0.08333 seconds interval. However it is only showing the last image.
HTML:
<!DOCTYPE html><html><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><script type="text/javascript" src="script.js"></script><title>page</title></head><body>
<img src="untitled.0001.jpg">
</body></html>
In javascript:
$(document).ready(function () {
$(document).keydown(function(e) {
switch(e.which) {
case 39: // right
for (var i = 1; i != 24; i++) {
setTimeout(function(){
$( "img" ).replaceWith( "<img src='image.000"+ i +".jpg'>");
},83);
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
How can I make it show all images within a timeout of 0.08333 seconds
Update: I tried solving it and came up with this:
$(document).ready(function () {
$(document).keydown(function(e) {
switch(e.which) {
case 39: // right
var count = 1;
while (count!=24) {
var waiting = 83 * count;
setTimeout(function() {$( "img" ).replaceWith( "<img src='avatar/walk/HumanWalk.000"+ count +".jpg'>");}, waiting);
count+=1;
}
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
Why is it still not working and showing last image only?
Use setInterval for such a case:
$(document).keydown(function(e) {
switch (e.which) {
case 39:
var c = 0;
var interval = setInterval(function() {
// set the source of your image to
// 'image.000' + (c++ -1) + '.jpg'
}, 83);
if (c === 24) clearInterval(interval);
}
});
Try this code
$(document).ready(function() {
$(document).keydown(function(e) {
switch (e.which) {
case 39: // right
for (var i = 1; i != 24; i++) {
(function(x) {
setTimeout(function() {
$("img").replaceWith("<img src='image.000" + x + ".jpg'>");
}, i*83);
})(i);
}
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});

Wait before function can be executed again

I'm playing around with some javascript and JQuery. I'm trying to do something specific each time the user scrolls. It works fine when I use a mouse with a scollwheel. But when I use the trackpad on my laptop it goes incredibly fast. I think it's because it executes the mousewheel function many times when scrolling. So I want to limit how often you can execute the function. Like with a 500ms delay between each call if the user keeps scrolling. It shouldn't delay the functions itself but run immediately and then wait 500ms before it can be executed again. Hope you understand.
Here's my code
$(window).bind('mousewheel', function(event) { // My mousewheel function.
if (event.originalEvent.wheelDelta >= 0) {
scroll(-1);
} else {
scroll(1);
}
});
/* Functions */
function scroll(dir) {
if (dir == -1) {
if (current > 0) {
current--;
}
} else {
if (current < list.size() - 1) {
current++;
}
}
var number = 100 * current;
var value = "translateY(-" + number + "vh)";
main.css("transform", value);
for (var i = 0; i < list.size(); i++) {
$('#nav li:nth-child(' + (i + 1) + ')').removeClass('active');
}
$('#nav li:nth-child(' + (current + 1) + ')').addClass('active');
}
You need to define a variable that indicate when to run the function or not. in this case is the "isScrolling" variable.
$(window).bind('mousewheel', function(event) { // My mousewheel function.
if (event.originalEvent.wheelDelta >= 0) {
scroll(-1);
} else {
scroll(1);
}
});
/* Functions */
var isScrolling = false; // This variable define when to run the function
function scroll(dir) {
if(isScrolling){
return;
}
isScrolling = true;
if (dir == -1) {
if (current > 0) {
current--;
}
} else {
if (current < list.size() - 1) {
current++;
}
}
var number = 100 * current;
var value = "translateY(-" + number + "vh)";
main.css("transform", value);
for (var i = 0; i < list.size(); i++) {
$('#nav li:nth-child(' + (i + 1) + ')').removeClass('active');
}
$('#nav li:nth-child(' + (current + 1) + ')').addClass('active');
setTimeout(function(){
isScrolling = false;
},500) // -> Here you can modify the time between functions call
}
What you need is a throttle function. This function wraps around other functions and checks the delay in ms and the id of the event.
/**
* #description delay events with the same id, good for window resize events, scroll, keystroke, etc ...
* #param {Function} func : callback function to be run when done
* #param {Integer} wait : integer in milliseconds
* #param {String} id : unique event id
*/
var throttle = (function () {
var timers = {};
return function (func, wait, id) {
wait = wait || 200;
id = id || 'anonymous';
if (timers[id]) {
clearTimeout(timers[id]);
}
timers[id] = setTimeout(func, wait);
};
})(),
You can use it like this:
$(window).on('mousewheel', function () {
throttle(function(){
var isScrollUp = event.originalEvent.wheelDelta >= 0 ? -1 : 1;
scroll(isScrollUp);
}, 500, 'my mousewheel event');
});
A nice example of underscore throttle -vs- debounce.

How to do an animation in Javascript with pause and play options?

function animate(elem,style,from,to,time) {
if (!elem) return;
var start = new Date().getTime(),
timer = setInterval(function() {
var step = Math.min(1, (new Date().getTime() - start) / time);
elem.style[style] = (from + step * (to - from))+'px';
if (step == 1) clearInterval(timer);
}, 25);
elem.style[style] = from + 'px';
}
Here is my code. and i need to pause and play in it
Finally i found the answer
function animate(elem,style,to,time,callback)
{
if(!elem) return;
_animating = true;
curAnimElem = elem; /*stores the current Element*/
curStyle = style; /*stores the current style*/
curTo = to; /*stores the current to 'px'*/
curCallback = callback; /*stores the current callbak function*/
if(style === 'left'){ from = elem.offsetLeft; }
else if(style === 'top'){ from = elem.offsetTop; }
var start = new Date().getTime(),
animTimer = setInterval(function()
{
if(!pauseV)
{
pauseTime = Math.round(time - (new Date().getTime()-start));
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1 ){ _animating = false; clearInterval(animTimer); if(callback){callback(); callback = null;} }
}
else{clearInterval(animTimer);}
},25);
elem.style[style] = from + 'px';
}
the above code is to animate the elements(left or top only). to PAUSE and PLAY, include the below code in pause/play event function.
function pauseFun()
{
if(pauseV)
{
pauseV = false;
if(_animating){ animate(curAnimElem,curStyle,curTo,pauseTime,curCallback); }
}
else if(!pauseV)
{pauseV = true;}
}
Its works for me......
Thanks.
Use clearInterval(timer) to pause the animation and then timer = setInterval(...) again to resume it. You would need to break the setInterval callback out into its own named function (inside the body of the first function) to make resuming easier.
try this:
var doAnimation=true;
var timer=0;
var start=undefined;
function animate(elem,style,from,to,time)
{
if(!elem && doAnimation) return;
if(start==undefined)start = new Date().getTime();
timer = setInterval(function(){
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1){
doAnimation=false;
clearInterval(timer);
elem.style[style] = from+'px';
start=undefined;
}},25);
}
function fun(){
doAnimation=!doAnimation;
if(doAnimation){play();}
else{pause();}
}
function play(){
animate( document.getElementById('box'),'left',0 , 200, 7000);
}
function pause(){
clearInterval(timer);
}
$(document).ready(function(){
play();
});
Check out the fiddle here:
http://jsfiddle.net/sunnykumar08/V9MHN/1/

Categories