Adding an increase / decrease speed button to slideshow - javascript

I need to make a slideshow that has an 'increase speed', 'decrease speed' button as well as pause/play. Im having a hard time and getting confused with the timeout/interval usage.
script:
// creates array and holds images
var imageArray = ['img/br1.jpg', 'img/br2.jpg', 'img/br3.png', 'img/br4.gif', 'img/br5.jpeg', 'img/br6.jpeg', 'img/br7.jpeg'];
// set the array to start at 0
var i = 0;
// create function 'slideShow'
function slideShow() {
// creates variable 'div' to load images into a div selected using 'getElementById'
var div = document.getElementById('slideshowdiv');
div.innerHTML = '<img src="' + imageArray[i] + '" />';
//increment i by 1
i++;
// checks if i is greater than or equal to the length
if(i >= imageArray.length) {
// if true, resets value to 0
i = 0;
};
// every 2 seconds change image
timer = setTimeout('slideShow()', 2000);
};
function stopShow() {
clearTimeout(timer);
};
function playShow() {
timer = setTimeout('slideShow()', 2000);
};
function increase() {
};
function decrease() {
};
html:
<body onload="slideShow();">
<div id="slideshowdiv"></div>
<div class="change">
<button onclick="stopShow()">Stop</button>
<button onclick="playShow()">Play</button>
<button onclick="increase()">Speed up slideshow</button>
<button onclick="decrease()">Slow down slideshow</button>
</div>

you could try to change the fixed value with a var:
// creates array and holds images
var imageArray = ['img/br1.jpg', 'img/br2.jpg', 'img/br3.png', 'img/br4.gif', 'img/br5.jpeg', 'img/br6.jpeg', 'img/br7.jpeg'];
// set the array to start at 0
var i = 0;
var speed = 2000;
var minSpeed = 3000;
var maxSpeed = 0;
// create function 'slideShow'
function slideShow() {
// creates variable 'div' to load images into a div selected using 'getElementById'
var div = document.getElementById('slideshowdiv');
div.innerHTML = '<img src="' + imageArray[i] + '" />';
//increment i by 1
i++;
// checks if i is greater than or equal to the length
if(i >= imageArray.length) {
// if true, resets value to 0
i = 0;
};
// every 2 seconds change image
timer = setTimeout('slideShow()', speed);
};
function stopShow() {
clearTimeout(timer);
};
function playShow() {
timer = setTimeout('slideShow()', speed);
};
function increase() {
if(speed -100 > maxSpeed )
speed -= 100;
};
function decrease() {
if(speed +100 <= minSpeed)
speed += 100;
};

What about something like this?
function playShow(playspeed) {
timer = setTimeout('slideShow()', playspeed);
};
function increase() {
var increase_to=10000;
playshow(increase_to);
};
function decrease() {
var decrease_to=100;
playshow(decrease_to);
}

Related

How can I get this timer script to function within a html/js element in ClickFunnels?

I've been trying to figure out how to get this to work in a single HTML/JS element in ClickFunnels.
I need to use a div tag instead of body tag but unfortunately I cannot use onLoad with divs as I've recently discovered.
I would highly appreciate any help on this as I've already spent a few hours trying to figure this out.
Here is the HTML
<body onLoad="startCount();">
<span class="timerz">Spots remaining: <span id="counterz">19</span></span>
</body>
Here is the JS
<script>
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var rand_no = Math.ceil(3 * Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var el = document.getElementById("counterz");
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 0) {
el.innerHTML = newNumber;
} else {
el.innerHTML = "1"; // This message is displayed when the counter reaches zero.
}
}
</script>
<script>
var timer;
function startCount() {
timer = setInterval(count, 500); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var rand_no = Math.ceil(3 * Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var el = document.getElementById("counterz");
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 0) {
el.innerHTML = newNumber;
} else {
el.innerHTML = "1"; // This message is displayed when the counter reaches zero.
}
}
document.addEventListener("DOMContentLoaded", (event) => {
startCount();
});

Increment issues

I have a timer going that adds 1 every second to the variable MenuTimer.
What I want is when the next button is pressed TillOpen The MenuTimer will stop having 1 added to it after that and a new variable to have 1 added instead PackTime
window.onload = function () {
var StopwatchSeconds= 00;
var StopwatchMinutes = 00;
var ShowSeconds = document.getElementById("seconds");
var ShowMinutes = document.getElementById("minutes");
var StartButton = document.getElementById("ButtonStart");
var Interval;
var menuTime;
var serviceTime;
var orders;
var menuAvg;
var serviceAvg;
StartButton.onclick= function(){
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
}
function startTimer () {
StopwatchSeconds++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
ShowMinutes.innerHTML = StopwatchMinutes;
StopwatchMinutes++;
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
}
}
Here's all of it. It half works but hopefully you get a better Idea of what i'm trying to go for.
var Interval;
var PackInterval;
var StopwatchSeconds= 00;
var StopwatchMinutes = 00;
var ShowSeconds = document.getElementById("seconds");
var ShowMinutes = document.getElementById("minutes");
var StartButton = document.getElementById("ButtonStart");
var TillOpenButton = document.getElementById("TillOpen");
var FinishButton = document.getElementById("Finish");
var ShowMenuTime = document.getElementById("MenuTime");
var ShowPackTime = document.getElementById("PackTime");
var ShowPackAvgSeconds = document.getElementById("PackerSeconds");
var ShowPackAvgMinutes = document.getElementById("PackerMinutes");
var ShowMenuAvgSeconds = document.getElementById("MenuMinutes");
var ShowMenuAvgMinutes = document.getElementById("MenuSeconds");
var DivisionSeconds = 60;
var TotalTime = 0;
var MenuTime = 0;
var PackTime = 0;
var AllMenuTimes = 0;
var AllPackTimes = 0;
var TotalMenuOrders = 0;
var TotalPackOrders = 0;
var MenuOrdersTotalSeconds = 0;
var PackOrdersTotalSeconds = 0;
var MenuAvgMinutes = 0;
var MenuAvgSeconds = 0;
var PackAvgSeconds = 0;
var PackAvgMinutes = 0;
StartButton.onclick = function(){
TotalMenuOrders + 1;
MenuTime = 0;
ShowMenuTime.innerHTML = MenuTime;
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
window.alert ("I work");
}
//This starts the timer. Inverval is a variable that holds the timer number.
function startTimer () {
StopwatchSeconds++;
TotalTime++;
MenuTime++;
AllMenuTime++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
StopwatchMinutes++;
ShowMinutes.innerHTML = StopwatchMinutes; // Makes this a string in html
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
}
// When the start button is pressed this function starts. it adds 1 to
Stopwatch, total and Menu every 1000 increments that Interval hits.
// This also says if StopwatchSeconds goes above 59 itll reset to 0 and if
its below itll keep counting.
TillOpenButton.onclick = function () {
PackTime = 0;
ShowPackTime.innerHTML = PackTime;
ShowMenuTime.innerHTML = MenuTime;
PackInterval = setInterval(startPackerTimer, 1000);
Interval+PackInterval;
clearInterval(Interval);
/* if (TotalMenuOrders < 1) {
AllMenuTimes / TotalMenuOrders = MenuOrdersTotalSeconds;
MenuOrderTotalSeconds % 60 = MenuAvgSeconds;
MenuAvgMinutes = Math.floor(MenuOrderTotalSeconds/60);
ShowMenuAvgMinutes.innerHTML = MenuAvgMinutes;
ShowMenuAvgSeconds.innerHTML = MenuAvgSeconds;
}
*/
}
// When this button is pressed it stops the first timer and the menu timer.
It then starts a new timer and function which add to the variable that will
show the total time.
// It does clear the variable Interval though
FinishButton.onclick = function (){
clearInterval(Interval);
ShowPackTime.innerHTML = PackTime;
clearInterval(PackInterval);
StopwatchSeconds = 0;
StopwatchMinutes = 0;
ShowSeconds.innerHTMl = 0 + StopwatchSeconds;
ShowMinutes.innerHTML = 0 + StopwatchMinutes;
AllPackTimes += PackTime;
TotalPackOrders++;
/*AllPackTimes/TotalPackOrders = PackOrderTotalSeconds;
PackOrderTotalSeconds % DivisionSeconds = PackAvgSeconds;
PackAvgMinutes = Math.floor(PackOrderTotalSeconds/60);
ShowPackAvgMinutes.innerHTML = PackAvgMinutes;
ShowPackAvgSeconds.innerHTML = PackAvgSeconds;*/
}
// When the Finish Button is pressed it clears everything. Resets
everything. except Menu Time, Total Time and PackTime. I need 3 new
variables to hold these to get the average.
function startPackerTimer () {
StopwatchSeconds++;
TotalTime++;
PackTime++;
if(StopwatchSeconds > 59) {
ShowSeconds.innerHTML = "0" + StopwatchSeconds;
StopwatchSeconds = 0;
StopwatchMinutes++;
ShowMinutes.innerHTML = StopwatchMinutes;
}
if(StopwatchSeconds < 59) {
ShowSeconds.innerHTML = StopwatchSeconds;
}
// Same deal but with the Till open button. Still adds onto
STopwatchSeconds so the variable doesn't change.
}
New solution, wich allows to create different timers and keep track of them:
//a method to setup a new timer
function Timer(Name){
this.timeElement=document.createElement("div");
(this.stopButton=document.createElement("button")).innerHTML="STOP";
(this.startButton=document.createElement("button")).innerHTML="START";
(this.Name=document.createElement("h1")).innerHTML=Name;
[this.Name,this.timeElement,this.startButton,this.stopButton].forEach(el=>document.body.appendChild(el));
this.stopButton.addEventListener("click",this.stop.bind(this));
this.startButton.addEventListener("click",this.start.bind(this));
this.seconds=0;
this.minutes=0;
}
Timer.prototype={
update:function() {
this.seconds++;
if(this.seconds > 59) {
this.seconds=0;
this.minutes++;
}
var secTemp="00"+this.seconds, minTemp="00"+this.minutes;
this.timeElement.innerHTML=minTemp.slice(minTemp.length-2)+":"+secTemp.slice(secTemp.length-2);
},
stop:function(){
if(this.interval) clearInterval(this.interval);
this.running=false;
if(this.onstop) this.onstop(this);
}
start:function(){
if(this.interval) clearInterval(this.interval);
this.interval = setInterval(this.update.bind(this), 1000);
this.running=true;
if(this.onstart) this.onstart(this);
}
};
This implements a Timer with OOP. So you can create multiple timers, and they wont influence each other.
You can create a timer like this:
var timer= new Timer("The Name");
You can also change events, set/read the times and check if running:
timer.start();//start the timer ( can also be done with the ui button)
timer.stop();
timer.onstart=()=>alert("Started!");
timer.onstop=()=>alert("Stopped!");
console.log(timer.running,timer.minutes,timer.seconds);
If you want to wait for multiple timers and to calculate the average if all of them stopped:
var timers=["Timer 1", "Timer 2"].map(name=>new Timer(name));//create two timers and store in array
timers.forEach(function(timer){
timer.running=true;
timer.onstop=function(){
if(timers.some(t=>t.running)) return;//if theres a running timer dont procceed
var seconds=timers.reduce((seconds,timer)=>seconds+=(timer.seconds+timer.minutes*60),0);
var average=seconds/timers.length;
alert("Average: "+average+"s");
};
});
http://jsbin.com/coduvohewu/edit?output
The old solution, adding a timer if the new button is pressed, and stops the old one then:
So you want to stop the current timer, and create a new one below that? Maybe you could refactor the code a bit, doing sth like this:
window.onload = function () {
var seconds= 0,minutes = 0;
var times=[];
var Interval;
var timeElement;
//a method to setup a new timer
function createTimer(dontsave){
if(times.length>3) return alert(times.map(el=>el.join(":")).join());
timeElement=document.createElement("div");
document.body.appendChild(timeElement);
if(!dontsave) times.push([minutes,seconds]);
}
createTimer(true);
//a method to let the timer run
function startTimer () {
seconds++;
if(seconds > 59) {
seconds=0;
minutes++;
}
var secTemp="00"+seconds,minTemp="00"+minutes;
timeElement.innerHTML=minTemp.slice(minTemp.length-2)+":"+secTemp.slice(secTemp.length-2);
}
//assign to buttons:
document.getElementById("ButtonStart").onclick= function(){
clearInterval(Interval);
Interval = setInterval(startTimer, 1000);
}
document.getElementById("ButtonNew").onclick=createTimer;
};
http://jsbin.com/mujisaweyo/edit?output
This simply creates a new div in the DOM if you press a button with the id ButtonNew . So the current time stays as a text in the old Element, and it keeps counting in the new one. Ive also added a zero filling...

Create infinite loop with moving divs using javascript or jQuery

I need to simulate a band that moves from left to right continuously, carrying 15 divs on it and moving them in a circle, like a carousel. When they reach the right margin to appear from the left.
I have the code that works for 1 div(more or less), but Im having troubles making the loop that includes all 15 divs.
What am I missing?
Here's what I have so far:
HTML
<body>
<div id="fooObject0">1</div>
<div id="fooObject1">2</div>
....
<div id="fooObject13">14</div>
<div id="fooObject14">15</div>
</body>
CSS
body {
font:76% normal verdana,arial,tahoma;
width:600px;
height:600px;
position:relative;
margin:0 auto;
border:1px solid;
}
div {
position:absolute;
left:0px;
top:8em;
width:55px;
height:70px;
line-height:3em;
background:#99ccff;
border:1px solid #003366;
white-space:nowrap;
padding:0.5em;
}
javascript
var foo = null; // object
function doMove(id) {
foo = document.getElementById(id);
foo.style.left = parseInt(foo.style.left)+1+'px';
setTimeout(doMove(id),20); // call doMove in 20msec
if(foo.style.left == "600px") {
foo.style.left = 0;
}
}
function init() {
for(i=0;i<15;i++){
var foo = document.getElementById('fooObject' + i); // get the "foo" object
foo.style.left = -i*55+'px'; // set its initial position to 0px
doMove('fooObject' + i); // start animating
console.log('fooObject' + i);
}
}
window.onload = init;
Thank you in advance!
It call an invalid function setTimeout(doMove(id), 20);.
doMove(id) return undefined, or you use "shared var" (Orientad Object) or doMove need return other function.
Note: var foo = null; // object this variable causes conflict when using setTimeout or setInterval
Try this (read my comments in code):
function doMove(id) {
return function() {
var foo = document.getElementById(id);//Global variable causes conflict when using `setTimeout` or `setInterval`
foo.style.left = parseInt(foo.style.left)+1+'px';
setTimeout(doMove(id),20); //setTimeout need an valid function
if(foo.style.left == "600px") {
foo.style.left = 0;
}
}
}
function init() {
for(i=0;i<15;i++){
var foo = document.getElementById('fooObject' + i);
foo.style.left = -i*55+'px';
doMove('fooObject' + i)(); //doMove need "()", because not run "direct"
console.log('fooObject' + i);
}
}
I modified the code for effect "carousel" and fix the problem with "left" (In 1 to 5 div):
function carrousel() {
var numberOfItems = 15; //Change this if needed
var delay = 1; //Change delay time if needed
var limitArea = 599; //Size limit your carousel area (600px, used 599 for limit with `>`)
var sizeObject = 58; //Width size of objects
//Don't change
var index = 0; //Current index
var allItems = []; //Indexed objects
//Get and index all objects
for(index = 0; index < numberOfItems; index++){//user var
allItems[index] = document.getElementById("fooObject" + index);
}
//Convert position left for int and detect "NaN"
var getPosition = function(pos) {
pos = parseInt(pos);
if (isNaN(pos)) {
return parseInt(-(index * sizeObject));
} else {
return parseInt(pos + 1);
}
};
var doMoveAll = function() {
var foo, post;
for(index = 0; index < numberOfItems; index++){//user var
foo = allItems[index];//Current object
pos = getPosition(foo.style.left);//Get position
//Detect if object are in out area
if(pos > limitArea) {
var beforeItem;
//Get before object for effect carousel
switch(index + 1) {
case 1:
beforeItem = "fooObject" + (numberOfItems - 1);
break;
default:
beforeItem = "fooObject" + (index - 1);
}
//Get position again, but used before object
pos = (
getPosition(document.getElementById(beforeItem).style.left) - sizeObject
);
foo.style.left = pos + "px";
} else {
foo.style.left = pos + "px";
}
}
//Timeout delay
window.setTimeout(doMoveAll, delay);
};
doMoveAll();//Init
};
window.onload = carrousel;

my jquery slider is running well but there is bug that it sometimes does'nt shows images on next or prev click

Found solution for the playing and stopping the slider.But problem is now with my next and prev links .these links some times does not shows any image.
my code is on the
http://jsfiddle.net/yogesh84/ftkLd/12/
var slides;
var cnt;
var amount;
var i;
var x;
var timer;
slides = jQuery('#my_slider').children();
cnt = jQuery('#counter');
amount = slides.length;
i=amount;
cnt.text(i+' / '+amount);
function run_prev() {
jQuery(slides[i]).fadeOut(1000);
i--;
if (i <= 0) i = amount;
jQuery(slides[i]).fadeIn(1000);
// updating counter
cnt.text(i+' / '+amount);
}
x=0;
function run_next() {
// hiding previous image and showing next
jQuery(slides[x]).fadeOut(1000);
x++;
if (x >= amount) x = 0;
jQuery(slides[x]).fadeIn(1000);
cnt.text(x+1+' / '+amount);
}
/***********start and stop functions***************/
function run() {
// hiding previous image and showing next
jQuery(slides[x]).fadeOut(1000);
x++;
if (x >= amount) x = 0;
jQuery(slides[x]).fadeIn(1000);
timer = setTimeout(run,2000);
}
function MySlider() {
timer = setTimeout(run,2000);
}
function stoper() {
clearTimeout(timer);
}
/***********end start and stop functions***************/
function slide_show(){
var timer;
if(jQuery('#slide_show').html()=='Play Slideshow')
{
jQuery('#slide_show').html('Stop Slideshow');
MySlider();
}
else
{
jQuery('#slide_show').html('Play Slideshow');
stoper()
}
}
// custom initialization
jQuery('#prev2').on("click",run_prev);
jQuery('#next2').on("click",run_next);
jQuery('#slide_show').on("click",slide_show);
I think you forgot to set timer
You declare at the top: timer but it is never filled.
So i think you should do:
timer = setTimeout( run, inetrval );
Also take the function outside of Run()
function run() {
}
if ( inetrval > 0 ) {
alert( inetrval );
run();
timer = SetTimeOut( run, inetrval )
}

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

Categories