setInterval script out of sync with innerFade - javascript

I'm creating an ad banner for a client using innerFade plugin for jQuery and some basic Javascripting to move the background image in the CSS. I'm using the setInterval method for the background image but it is getting out of sync with innerFade. Below is the code I have placed in the head of the page. I'm just trying to find an effective and efficient method for syncing the two up.
$(document).ready(function () {
$('#slides').innerfade({
animationtype: 'fade',
speed: 2000,
timeout: 5000,
type: 'sequence',
containerheight: '326px'
});
});
// Code for panning of background images
var scrollSpeed = 48.58;
var step = 1;
var interval = 0;
var secs = 0;
var img1Pos = 0;
var img2Pos = 0;
var img3Pos = 0;
function scrollBg() {
interval += step;
secs = (interval / 20);
while (secs < 1) {
$(this).hide("slide", {
direction: "down"
}, 1000);
img3Pos -= step;
$('#image3').css("background-position", "0 " + img3Pos + "px");
break;
}
while (secs < 6) {
img1Pos -= step;
$('#image1').css("background-position", "0 " + img1Pos + "px");
break;
}
while (secs < 11 && secs > 5) {
img2Pos -= step;
$('#image2').css("background-position", img2Pos + "px 0");
break;
}
while (secs < 15 && secs > 10) {
img3Pos -= step;
$('#image3').css("background-position", "0 " + img3Pos + "px");
break;
}
if (secs == 15) {
interval = 0;
img1Pos = 0;
img2Pos = 0;
}
if (secs == 1) {
img3Pos = 0;
}
}
var init = setInterval("scrollBg()", scrollSpeed);

I think the problem here is that Javascript is not multi-threaded. You are trying to emulate multi-threading by moving the image bit by bit, but the end result will never be perfectly in sync unless you write your own fade implementation.
Also you could replace while (secs < 6) { .. break; } with if (secs < 6).

Related

Increase and decrease SVG shape - JS

I would like you to help me for a thing here, for a function to increase and then decrease SVG shape when it hits limit.
It should go from 3 to 6 and then 6 to 3 and so on... but instead it goes from 3 to 6 and then 6 to minus infinite. And I don't understand why.
Here is my code :
var size = 3;
var sizeManager = 1;
function increaseAnimation(el){
var elem = document.getElementById(el);
elem.style.transform = "scale("+size+")";
timer = setTimeout('increaseAnimation(\''+el+'\',3000)');
size=size+0.005*sizeManager;
if(size >= 6){
sizeManager=sizeManager*-1;
}
if (size <= 3){
sizeManager=sizeManager*+1;
}
}
Your weird setTimeout implementation, with bound was broken.
There's also the issue that your sizeManager is not properly reflecting:
function increaseAnimation(id, interval) {
var size = 1;
var velocity = 0.05;
var elem = document.getElementById(id);
function iterate() {
elem.style.transform = "scale(" + size + ")";
size += velocity;
if (size > 2 || size < 1) {
velocity *= -1; // velocity reflected
}
}
var timer = setInterval(iterate, interval);
return function stop() {
clearInterval(timer)
}
}
I also added a stop function which you can call at a later point.
var stopper = increaseAnimation("content", 16);
setTimeout(stopper, 5000);
The error is with the line sizeManager=sizeManager*+1; Multiplying a number by one doesn't change it. You basically want to toggle sizeManager between -1 and +1, and you can do so by multiplying by -1, regardless of whether it is currently negative or positive.
I've tested this code and it seems to work:
var size = 3;
var sizeManager = 1;
function increaseAnimation(el) {
var elem = document.getElementById(el);
elem.style.transform = "scale(" + size + ")";
timer = setTimeout("increaseAnimation('" + el + "', 3000)");
size += 0.005 * sizeManager;
if (size >= 6 || size <= 3) {
sizeManager *= -1;
}
}
Full HTML for a POC demo at: https://pastebin.com/GW0Ncr9A
Holler, if you have questions.
function Scaler(elementId, minScale, maxScale, deltaScale, direction, deltaMsecs) {
var scale = (1 == direction)?minScale:maxScale;
var timer = null;
function incrementScale() {
var s = scale + deltaScale*direction;
if (s < minScale || s > maxScale) direction *= -1;
return scale += deltaScale*direction;
};
function doScale(s) {
document.getElementById(elementId).style.transform = 'scale(' + s + ')';
};
this.getDeltaMsecs = function() {return deltaMsecs;};
this.setTimer = function(t) {timer = t;};
this.run = function() {doScale(incrementScale());};
this.stop = function() {
clearInterval(timer);
this.setTimer(null);
};
};
var scaler = new Scaler('avatar', 3, 6, .05, 1, 50);
function toggleScaler(ref) {
if ('run scaler' == ref.value) {
ref.value = 'stop scaler';
scaler.setTimer(setInterval('scaler.run()', scaler.getDeltaMsecs()));
}
else {
scaler.stop();
ref.value = 'run scaler';
}
};

My script needs page refresh for it to run

Every time I load my page for the first time my script does not load, I need to refresh the page at least 3 times for it to run. How can I make my script run without a page refresh? This particular script is in BABEL.
'use strict';
var deg = 0;
var index = 0;
$('#' + index).css('opacity', '1');
$('.navbar').contextmenu(function () {
return false;
});
$('.navbar').on('mousewheel', function (e) {
var move = -60;
var nextIndex = nextIndex = (index + 1) % 6;
if (e.originalEvent.wheelDelta / 120 <= 0) {
// wheel up
move = 60;
nextIndex = index -1 < 0 ? 5 : index - 1;
}
$('.scroll-list').css('transform', 'rotateX(' + (deg + move) + 'deg)');
$('#' + index).css('opacity', '0.01');
$('#' + nextIndex).css('opacity', '1');
index = nextIndex;
deg = deg + move;
event.stopPropagation();
console.timeEnd('cache');
});
And what if you wrapped your code inside a window.onload function?
window.onload = function() {
// your code
}
Your code will only run when the html document is "ready" and fully loaded.
You are running Javascript that depends on page elements and the javascript is executed before the elements are on the page;
Wrapp all your code inside document.ready function
$(document).ready(function () {
var deg = 0;
var index = 0;
$('#' + index).css('opacity', '1');
$('.navbar').contextmenu(function () {
return false;
});
$('.navbar').on('mousewheel', function (e) {
var move = -60;
var nextIndex = nextIndex = (index + 1) % 6;
if (e.originalEvent.wheelDelta / 120 <= 0) {
// wheel up
move = 60;
nextIndex = index - 1 < 0 ? 5 : index - 1;
}
$('.scroll-list').css('transform', 'rotateX(' + (deg + move) + 'deg)');
$('#' + index).css('opacity', '0.01');
$('#' + nextIndex).css('opacity', '1');
index = nextIndex;
deg = deg + move;
event.stopPropagation();
console.timeEnd('cache');
});
});
Wrap your code in ready function, so that your JavaScript executes after DOM is loaded.

How to Stop Interval After on Full Run

Can you please take a look at this demo and let me know how I can stop the animation and interval after reaching 100% and filling the progress bar
I tried adding clearInterval(myVar); to the end of interval but this stops incrementting the percentage text
$(".progress-bar").animate({
width: "100%"
}, 3000);
var myVar=setInterval(function(){myTimer()},1);
var count = 0;
function myTimer() {
if(count < 100){
$('.progress').css('width', count + "%");
count += 0.05;
document.getElementById("demo").innerHTML = Math.round(count) +"%";
// code to do when loading
}
else if(count > 99){
// code to do after loading
count = 0;
}
}
clearInterval(myVar);
Don't use a timer for this. jQuery provides a way for you to listen to the progress of the animation:
$(".progress-bar").animate({
width: "100%"
},{
duration: 3000,
progress: function(_, progr) {
$('#demo').text( Math.round(100 * progr));
}
});
See your updated fiddle
NB: I changed your demo element to a span, as a p will break the % to the next line.
You need to put the code of clearing the interval in the block where you handle the finishing of loading.
var myVar = setInterval(function() {
myTimer()
}, 1);
var count = 0;
function myTimer() {
if (count < 100) {
$('.progress').css('width', count + "%");
count += 0.05;
document.getElementById("demo").innerHTML = Math.round(count) + "%";
// code to do when loading
} else if (count > 99) {
// code to do after loading
count = 0;
// loading is done, clear the interval
clearInterval(myVar);
}
}

progress bar function breaking after one call

Fiddle
In the code provided if you click battle it will complete the battle action and fill the progress bar 3 times(equal to var auto) if you let it finish that and then click battle again the progress bar will reach val 25 and freeze. Why is this and how can I fix it?
var auto = 3;
var nb = 0;
var progress = function(sec) {
if($('#bar').val() === 0) {
$('#dam').html("You have hit the " + $('#monsters').val() + " for 5 damage").fadeIn(400);
}
if($('#bar').val() >= 75) {
$('#dam').html("You have hit the " + $('#monsters').val() + " for 5 damage").fadeOut(800);
}
var interval = 1000; //milliseconds
setTimeout(function() {
sec = sec + 25;
$('#bar').val(sec);
if (sec > 100) {
$('#bar').val(0);
sec = 0;
nb++;
}
if (nb < auto) progress(sec); //call self with new value
}, interval)
}
$('#battle').click(function() {
progress(0); //initialize progress bar
});
The problem is that your nb variable is not reset. Following code/condition should work:
if (nb < auto)
progress(sec);
else
nb = 0;
See working JSFiddle

I want to show a image moving from right top corner to left bottom corner in simple html

onmouseover() I am calling this function
function move_arrow() {
document.getElementById('arrow1').style.display = "block";
j = 100;
for (var i = 1000; i > 260; i--) {
document.getElementById('arrow1').style.left = i + 'px';
document.getElementById('arrow1').style.top = j + 'px';
if (j < 440) {
j = j + .5;
}
//alert();
}
}
With alert its shows image moving to desired position otherwise its not. I know with alert it gets sufficient time to execute the function.
What can be the right solution for this in simple html and javascript which works in all browsers.
You may use setInterval for example:
function move_arrow() {
document.getElementById('arrow1').style.display = "block";
j = 100;
i = 1000;
var intervalId = setInterval(
function() {
i--;
document.getElementById('arrow1').style.left = i + 'px';
document.getElementById('arrow1').style.top = j + 'px';
if (j < 440) {
j = j + .5;
}
if (i < 240)
clearInterval(intervalId); //switch off setInterval
},
10 //execute this function every 10ms
);
}

Categories

Resources