Using a return/stop function on click - javascript

Currently closee to finishing a slideshow using html and JavaScript. My last problem is creating stop button which needs to use a return function (I assume) Or some sort of exit function. It is an image slideshow that runs automatically, can be paused, skip image, go back an image and so on. I'd like the stop button to kill the autoRun function and set the image back to the first default image. I've set up a function which I'm guessing is totally wrong as it is not working.
The HTML
<td class="controls">
<button onClick="autoRun()">Start</button>
<button onClick="changeImage(-1); return false;">Previous Image</button>
<button onClick="pause();">pause</button>
<button onClick="changeImage(1); return false;">Next Image</button>
<button onClick="Exit();">Exit</button>
</td>
</tr>
All buttons are working besides the last one
JavaScript
var images = ["HGal0.jpg", "HGal1.jpg", "HGal2.jpg", "HGal3.jpg", "HGal4.jpg", "HGal5.jpg", "HGal6.jpg", "HGal7.jpg", "HGal8.jpg", "HGal9.jpg", "HGal10.jpg", "HGal11.jpg", "HGal12.jpg", "HGal13.jpg", "HGal14.jpg", "HGal15.jpg"];
var interval = setInterval("changeImage(1)", 2000);
var imageNumber = 0;
var imageLength = images.length - 1;
function changeImage(x) {
imageNumber += x;
// if array has reached end, starts over
if (imageNumber > imageLength) {
imageNumber = 0;
}
if (imageNumber < 0) {
imageNumber = imageLength;
}
document.getElementById("slideshow").src = images[imageNumber];
return false;
}
function autoRun() {
interval = setInterval("changeImage(1)", 2000);
}
function pause(){
clearInterval(interval);
interval = null;
}
function Exit(){
return;
}
I'm not fully understanding the return statement in the Exit function, as most examples I've looked at run the function when an 'if' statement is met, whereas I'd like mine to execute when the Stop button is clicked. Thanks

A return statement simply exits the function in which it appears, it doesn't cause other things to stop. So this:
function Exit(){
return;
}
...has the same effect as this:
function Exit() { }
That is, the function doesn't do anything at all.
I'd like the stop button to kill the autoRun function and set the image back to the first default image.
OK, so have your Exit() function call your other functions:
function Exit() {
pause(); // this will stop the slideshow
imageNumber = 0; // reset to the first image
changeImage(0); // change to that image
}

Related

Jquery Timer that starts and stops with same button

I can't for the life of my figure out how to get this to work bug free.
The button in the code below needs to do three things.
Start a countdown when clicked (works)
End the countdown automatically, and reset itself when it reaches 0(works)
Reset itself prematurely if its clicked in the middle of a countdown(works, sort of)
Bug: when clicked repeatedly it starts multiple countdowns, and more or less breaks. It needs to either reset itself or start a countdown if clicked repeatedly. There should never be more than one countdown.
It works fines as long as people press the button, wait a second, and then press it again to stop it.
The bug I'm running into is if someone spam clicks it, it starts multiple countdowns and generally just breaks the button. I've tried a lot of different methods to fix it, and this is the closest I've gotten.
var i = 29;
let running=false;
$("#startButton").click(function () {
if(running==false){
var countdown = setInterval(function () {
$("#startButton").text("Reset Timer");
running=true;
$("#stopWatch").html(i);
i--;
if (i <0)
{
$("#startButton").text("Start Timer");
running=false;
clearInterval(countdown);
i = 29;
$("#stopWatch").html(i);
}
$("#startButton").click(function () {
$("#startButton").text("Start Timer");
running=false;
clearInterval(countdown);
i = 29;
$("#stopWatch").html(i+1);
});
}, 1000);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch">30</div>
<button id="startButton">Start Timer</button>
Welcome to Stack Overflow #William!
I'm not sure what this means: Reset itself prematurely if its clicked in the middle of a countdown(works, sort of). But I managed to fix your bug on spamming button click and for item 3, i just do reset the countdown from initial state. See snippets below:
// Get attribute value from div `stopwatch`. This is for resetting from default value.
var initial = $('#stopWatch').attr("value");
// Assigned initial value to var i.
var i = initial;
$("#stopWatch").html(i);
let running = false;
// Created a separate function to call from button click.
function run(timer = true) {
if (timer) {
running = true;
$("#startButton").text("Reset Timer");
$("#stopWatch").html(i);
var countdown = setInterval(function () {
i--;
$("#stopWatch").html(i);
if (i <= 0) {
running = false;
$("#startButton").text("Start Timer");
clearInterval(countdown);
i = initial;
$("#stopWatch").html(i);
}
}, 1000);
} else {
running = false;
clearInterval(countdown);
i = 0;
$("#startButton").text("Start Timer");
}
}
$("#startButton").click(function () {
// Check if its not running and var i is not 0
if(!running && i != 0) {
run();
// Check if its running and var i is not 0 to ensure that if someone spam the button it just reset the countdown.
} else if (running && i != 0) {
// Will return the else{} on function run().
run(false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch" value="30"></div>
<button id="startButton">Start Timer</button>
Added some comments on the snippet. Feel free to ask if you have any questions.

Play or pause CSS animation using JavaScript

I'm unsure if the following lines of JavaScript are correct. On the click of a button, the following JavaScript function is called. This function should pause the CSS animation when clicked once and resume the animation if clicked again:
function myFunction()
{
document.getElementById("sky").style.animationPlayState = "paused | running";
}
The logic for determining what state to change it to, needs to be done outside the quotes. You are probably looking more for something like this:
function myFunction()
{
var sky = document.getElementById("sky");
if(sky.style.animationPlayState == "paused")
{
sky.style.animationPlayState = "running";
}
else
{
sky.style.animationPlayState = "running";
}
}
Or all in one line like this:
element.style.animationPlayState = running ? 'paused' : 'running';

Countdown function isn't actually counting down

I have a function in my .js file that is supposed to display a countdown from 10 - 0. Once it hits 0, it should open up a second page. I don't have the part where it opens the page written yet, but that isn't my current problem. My problem is that the countdown will display the number 1, and do nothing else. I'm not really sure why.
Here's the countdown function
function startCountdown() {
for (var i = 10; i >= 0; i--) {
document.getElementById("countdown").value = i;
}
}
Here is the function that calls it
function startAdPage() {
setInterval(changeAd(), 2000);
setInterval(startCountdown(), 1000);
}
Finally, here is the HTML code that it is sending to. Everything is started by the body tag calling the onload method. I know that part works, since I have it doing something else that is working properly.
<div id="counter">
<p>The Central Valley Realtors home page will display in
<input type="text" value="" class="countdown"/>
seconds</p>
</div>
The first argument to setInterval is a function. You're not passing the function, you're calling the function and passing whatever it returns, since you have () after the function name.
Also, you're not waiting between updates to the countdown field. Javascript is single-threaded, the page doesn't update until the script returns. You need this:
function startAdPage(){
var curCounter = 10;
function startCountdown() {
document.getElementById("countdown").value = curCounter;
curCounter--;
if (curCounter == 0) {
clearInterval(countdownInterval);
}
}
setInterval(changeAd, 2000);
var countdownInterval = setInterval(startCountdown, 1000);
}
Your loop inside of startCountdown is running all the way to the end of the loop, so the value ends up 0. Also, you are supposed to pass either an Anonymous function or an unexecuted function to setInterval and clearInterval without parameters. When you add () at the end of a function name you are executing the function. Change the the <input type='text' class='countdown' /> to <input type='text' id='countdown' />, then try the following:
function countdown(begin, end, interval, outputElement){
var repeat = setInterval(function(){
if(outputElement.innerHTML){
outputElement.innerHTML = begin--;
}
else{
outputElement.value = begin--;
}
if(begin === end)clearInterval(repeat);
}, interval);
}
countdown(10, 0, 1000, document.getElementById('countdown'));

Restarting setInterval in javaScript

var myImage = document.getElementById("mainImage");
var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg",
"_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
I tried to refactor this question restarting a setInterval, but couldn't get it right. Any help would be appreciated!
***Added context****
Basically I have a bunch of images that cycle through and stop upon clicking them. I'd like to restart the cycling upon clicking again...
var intervalHandle = setInterval(changeImage,5000);
//Basically I want a clearInterval on a click and then restart this changing image function it.
myImage.onclick = function(){
clearInterval(intervalHandle);
intervalHandle = setInterval(changeImage,5000);
};
I expect the problem is that setInterval doesn't fire immediately, and you're expecting it to call changeImage as soon as you click myImage. The first call to changeImage will be 5 seconds after clicking the image. You could do something like this to call changeImage immediately:
myImage.onclick = function () {
clearInterval(intervalHandle);
intervalHandle = setInterval(changeImage, 5000);
changeImage();
};
Another choice is to do away with intervals entirely (as with this answer) — intervals can queue up when the window isn't focused in some browsers, so you could have changeImage set its own timeouts:
var timeoutHandle = setTimeout(changeImage, 5000);
function changeImage() {
// ...
timeoutHandle = setTimeout(changeImage, 5000);
}
myImage.onclick = function () {
clearTimeout(timeoutHandle);
changeImage();
};
Basically I have a bunch of images that cycle through and stop upon clicking them. I'd like to restart the cycling upon clicking again...
Well why didn't you say so? ;)
So you want to start the interval if its not started, and stop it if it is started.
var intervalHandle = setInterval(changeImage, 5000); // start the interval by default
var running = true; // true if the interval is running, false if its not.
myImage.onclick = function(){
if (running) {
clearInterval(intervalHandle); // stop interval
running = false; // mark interval as stopped
} else {
intervalHandle = setInterval(changeImage, 5000); // start interval
running = true; // mark interval as started
changeImage(); // also change the image right now
}
};
the only reason why i think this would not work is if you define intervalHandle in a "dom ready" event or some other function so try putting it in global scope rather than defining it.
EDIT: sorry for the first reply it was indeed false beacause i didnt had full information of what you wanted to do so home this will help you
var intervalHandle = setInterval(changeImage,5000);
myImage.onclick = function(){
if (intervalHandle > -1) {
clearInterval(intervalHandle);
intervalHandle = -1;
} else {
intervalHandle = setInterval(changeImage,5000);
}
};

javascript - ignore timeout on click

I have a slideshow which works fine, leaving a 3 second gap between images.
I also have a set of dynamically generated links which when clicked on, the next image is corresponds to that link.
What I want to do is skip the 3 second time out when one of these links is clicked - then restart the timeout after the image is changed.
Code below:
$(document).ready(function() {
var images=new Array();
var totalimages=6;
var totallinks=totalimages;
var nextimage=2;
while (totallinks>0) {
$(".quicklinks").prepend("<a href='#' class='"+(parseInt(totallinks))+"' onclick='return false'>"+(parseInt(totallinks))+"</a> ");
totallinks--;
}
function runSlides() {
if(runSlides.opt) {
setTimeout(doSlideshow,3000);
}
}
function doSlideshow()
{
if($('.myImage').length!=0)
$('.myImage').fadeOut(500,function(){slideshowFadeIn();$(this).remove();});
else
slideshowFadeIn();
}
function slideshowFadeIn()
{
if(nextimage>=images.length)
nextimage=1;
$('.container').prepend($('<img class="myImage" src="'+images[nextimage]+'" style="display:none;">').fadeIn(500,function() {
runSlides();
nextimage++;
}));
}
if(runSlides.opt) {} else {
images=[];
totalimages=6;
while (totalimages>0) {
images[totalimages]='/images/properties/images/BK-0'+parseInt(totalimages)+'.jpg';
totalimages--;
}
runSlides.opt = true;
runSlides();
}
$(".quicklinks a").live('click', function() {
nextimage=$(this).attr("class");
});
});
You can stop a timeout using this code:
var t = setTimeout(myFunction,3000);
clearTimeout(t);
Using this, you can abort your timeout when the user clicks the button and call the function directly. Then you can restart the timeout.
Hope this helps.

Categories