progress bar function breaking after one call - javascript

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

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';
}
};

How to stop javascript from executing after clicking stop button?

<script>
function timer(duration, elementId, scoreID, mistakesID){
var start = Date.now();
var min, sec, diff;
var scoreComputed = false;
function timerCompute(){
diff = duration - (((Date.now() - start) / 1000) | 0);
min = ( diff / 60 ) | 0;
sec = ( diff % 60 ) | 0;
//If less than 10, add zero in front of it to keep tens place
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
elementId.textContent = min + ":" + sec;
if ( diff <= 0 ){
elementId.textContent = "0:00";
if (!scoreComputed){
score /= (duration / 60);
score = Math.round(score);
scoreComputed = true;
}
scoreID.textContent = score;
document.getElementById("usertext").readOnly = true;
$("#resultsContainer").fadeIn(1500);
if(mistakes.length > 0){
var mistakesStr = "";
for(var i = 0; i < mistakes.length; i++){
mistakesStr += i > 0 ? ", " : "";
usertextArr[mistakes[i]] = usertextArr[mistakes[i]] === "" ? "blank" : usertextArr[mistakes[i]];
mistakesStr += usertextArr[mistakes[i]] + " instead of " + textArr[mistakes[i]];;
}
mistakesID.textContent = mistakesStr;
$("#mistakesContainer").fadeIn(1500);
$('.type-test-wrapper').css("filter","blur(3px)");
}
return;
}
};
timerCompute();
setInterval(timerCompute, 1000);
}
var timerStarted = false;
$('#usertext').on('keydown', function() {
var time = 60 * 0.1,
display = document.querySelector('#time');
scoreDisplay = document.querySelector('#score');
mistakesDisplay = document.querySelector('#mistakes');
if ( timerStarted === false ){
timer(time, display, scoreDisplay, mistakesDisplay);
typeTest();
timerStarted = true;
}
});
</script>
The above script is from a typing test. When the typing test ends, the above script fades in a result box. I was trying to modify the code. I want to add a close button to the result box so that user can close the box after he viewed the result. So I added the below code to close the result box.
<script type='text/javascript'>
jQuery(document).ready(function($){
$('.close-btn, body').click(function(){
$('.type-test-wrapper').css("filter","blur(0px)");
$('#resultsContainer, #mistakesContainer').stop().fadeOut('medium');
});
});
</script>
The problem I am facing is that when I click on close button, the box fades out #resultContainer, #mistakesContainer but as soon the box gets faded, it again fades in. No matter how many times i close the box, it fades in again and again. I want that once user click on close button the box should not get displayed again. How to fix the code so that once the the box fades out, the first code doesn't again fades in the box. I am new at javascript. Thank you for help.
Live webpage here https://htmlpreview.github.io/?https://raw.githubusercontent.com/dp121112/type-testing/master/test.html
I think you're not clearing the interval
try to assing interval as follow.
var intrvl= setInterval(timerCompute, 1000);
and clear it when its done
scoreID.textContent = score;
document.getElementById("usertext").readOnly = true;
$("#resultsContainer").fadeIn(1500);
clearInterval(intrvl);

Modal timer progress bar

I have a modal for when a button is clicked. The modal popups and closes when the timer is up, currently 5 seconds. However, I would like to create a progress bar which shows the timer going down, no numbers just a bar that moves.
Here is what I already have: https://jsfiddle.net/cde2cup0/. YOU MUST CLICK THE BUTTON 'ADMINISTRATION' for the modal.
And here's what I want to achieve. I know my Photoshop skills aren't on point, was rushing:
The white bar at the bottom is the progress bar.
I did try this but wasn't suitable for what I needed so didn't work.
var start = new Date();
var maxTime = 835000;
var timeoutVal = Math.floor(maxTime/100);
animateUpdate();
function updateProgress(percentage) {
$('#pbar_innerdiv').css("width", percentage + "%");
$('#pbar_innertext').text(percentage + "%");
}
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
var perc = Math.round((timeDiff/maxTime)*100);
if (perc <= 100) {
updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
}
}
Reference: jQuery progress timer bar
I don't know if correctly understood your question, but hope that helps:
Fiddle: https://jsfiddle.net/cde2cup0/2/
var progressBar = document.getElementById('myProgressBar');
function setAnimation(timeInSeconds, callbackFunction) {
var count = 0;
var interval = setInterval(function() {
if (count == timeInSeconds) {
callbackFunction();
clearInterval(interval);
}
progressBar.style.width = (100 * count / timeInSeconds) + '%';
count++;
}, 1000);
};

jQuery progress timer bar

I have a progress timer bar in jQuery - here is an example http://jsfiddle.net/6h74c/
If I have time values in milliseconds, (600000 = 10 minutes, 300000 = 5 minutes, etc), how can I make the bar increment for that period of time?
In the jsfiddle link, I'm trying to set the progress bar to increase for 835000ms.
However, the setTimeout() determines how often the bar will increase and it is also basing it off of width percentage, which doesn't seem accurate - should I be doing this differently?
function updateProgress(percentage) {
$('#pbar_innerdiv').css("width", percentage + "%"); // probably not ideal
$('#pbar_innertext').text(percentage + "%");
}
function animateUpdate() {
perc++;
updateProgress(perc);
if(perc < 835000) {
timer = setTimeout(animateUpdate, 50); // probably not ideal either?
}
}
Fiddle Example
I would do something like:
var start = new Date();
var maxTime = 835000;
var timeoutVal = Math.floor(maxTime/100);
animateUpdate();
function updateProgress(percentage) {
$('#pbar_innerdiv').css("width", percentage + "%");
$('#pbar_innertext').text(percentage + "%");
}
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
var perc = Math.round((timeDiff/maxTime)*100);
if (perc <= 100) {
updateProgress(perc);
setTimeout(animateUpdate, timeoutVal);
}
}
Simply do some good old fashioned math. It doesnt seem right because you're giving width percentage as the value of the "tick" which will eventually be 835000! Meaning you eventually have a width of "835000%"!!!
Example
var timer = 0,
perc = 0,
timeTotal = 835000,
timeCount = 50;
function updateProgress(percentage) {
var x = (percentage/timeTotal)*100,
y = x.toFixed(3);
$('#pbar_innerdiv').css("width", x + "%");
$('#pbar_innertext').text(y + "%");
}
function animateUpdate() {
if(perc < timeTotal) {
perc++;
updateProgress(perc);
timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
clearTimeout(timer);
perc = 0;
animateUpdate();
});
});
jsFiddle Demo
Description
This just simply increases the progress every 10ms...since you know the time it takes, take that time and divide by 100 then make that your timeinterval in var timer = setInterval(updateProgressbar, 10);
HTML
<div id="progressbar"></div>
JS
var progress = 0;
var timer = setInterval(updateProgressbar, 10);
function updateProgressbar(){
$("#progressbar").progressbar({
value: ++progress
});
if(progress == 100)
clearInterval(timer);
}
$(function () {
$("#progressbar").progressbar({
value: progress
});
});
JS Fiddle Just for you
JS
var progress = 0;
var timer = setInterval(updateProgressbar, 8350);
function updateProgressbar(){
$("#progressbar").progressbar({
value: ++progress
});
if(progress == 100)
clearInterval(timer);
}
$(function () {
$("#progressbar").progressbar({
value: progress
});
});
You probably want something like this:
var currentTime = new Date().getTime();
perc = (currentTime - StarTime)/duration;
If set StartTime like that too you can calculate the percentage on every update.

setInterval script out of sync with innerFade

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).

Categories

Resources