How to trigger a setInterval function on a user click? - javascript

I'm trying to write a JS timer that will be triggered by a user click on the button with id="start".
I've got the timer itself working correctly, but when I try to add code to initiate the timer on the button click (id="start") I break it and am not sure why.
Any help would be greatly appreciated!
Here is the JS code:
$(document).ready(function(){
var count = 0;
$('#start').click(function(){
setInterval(function(){
count++;
$('#timer').html(count + ' tacos seconds');
},1000);
});
});

$(document).ready(function() {
$('#start').click((function(container) {
var interval;
return function() {
if(interval) clearInterval(interval);
var count = 0;
interval = setInterval(function() {
count++;
$(container).html(count + ' tacos seconds');
}, 1000);
};
})("#timer"));
});

$(document).ready(function() {
var count = 0;
var myInterval = null;
$('#start').click(function(){
myInterval = setInterval(function(){
count++;
$('#timer').html(count + ' tacos seconds');
},1000);
});
});
When setting your setInterval in the scope of the click handler, try assigning it to a variable to hold the interval declared up a level. This has typically always worked for me.

Not sure exactily what your objective is, but maybe you'd want to try something like this:
var startInterveal;
var timerStarted = false;
var count =0;
$(document).ready(function () {
$('#start').click(function () {
if (!timerStarted) {
timerStarted = true;
count =0;
$(this).attr('disabled', 'disabled');
startInterveal = setInterval('tick();', 1000);
}
});
});
function tick() {
count++;
$('#timer').html(count + ' tacos seconds');
}

Here is a 2nd answer if you really want to go nuts and have something resuable:
$(document).ready(function() {
$('#start').click(overboard("#timer"));
$('#start2').click(overboard("#timer2"));
});
function overboard(container) {
var interval;
return function() {
if (interval) clearInterval(interval);
var count = 0;
interval = setInterval(function() {
count++;
$(container).html(count + ' tacos seconds');
}, 1000);
};
}

Related

how to make it have a wait until it executes a new code

So how do I make it wait 1000 milliseconds until it executes a different code(btw, What is the JavaScript version of sleep()? IS NOT helping me, so PLEASE don't close this question(and I'm not very good with JavaScript)).
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Start</title>
</head>
<body>
<div id="changeText" style="font-family:verdana;"><br><br>
Press ENTER to continue</div>
<script>
document.addEventListener('keydown',function(e){
if(e.keyCode==13){
newPageTitle = 'Executing...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Loading...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Fetching Data...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Done!';
document.title = newPageTitle;
//wait goes here
window.location.href=('https://example.com');
}
});
</script>
<script>
var text = ["<br><br>Press ENTER to continue_", "<br><br>Press ENTER to continue"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 700);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
}
}
</script>
</body>
</html>
what I want it to do is whenever you press enter it changes the title, then it waits 1000 milliseconds to change the tile again, and then it waits 680 milliseconds to redirect you to another webpage (also for some reason when it's in the code snippet you have to click the snippet area and the you can press enter).
To do your animation on the document title, that would be a serie of nested setTimeout() function looking like this:
setTimeout(function () {
document.title = "Executing...";
setTimeout(function () {
document.title = "Loading...";
setTimeout(function () {
document.title = "Fetching Data...";
setTimeout(function () {
document.title = "Done!";
setTimeout(function () {
window.location.href = "https://example.com";
}, 1000);
}, 4000);
}, 3000);
}, 2000);
}, 1000);
I agree that is ugly. And you would have to calculate the added delays from outer to inner... So you could have a function to set the timeouts and make your code readable and maintainable.
Notice that nice looking script:
wait(1000, 'Executing...')
wait(2000, 'Loading...')
wait(3000, 'Fetching Data...')
wait(4000, 'Done!')
wait(1000)
Here is a demo where I console logged the title texts... Because we won't see the effect otherwize, since the snippet is an iframe.
document.addEventListener('keydown', function(e) {
if (e.keyCode == 13) {
wait(1000, 'Executing...')
wait(2000, 'Loading...')
wait(3000, 'Fetching Data...')
wait(4000, 'Done!')
wait(1000)
}
});
var text = ["<br><br>Press ENTER to continue_", "<br><br>Press ENTER to continue"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 700);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
}
}
// A global variable to sum up the delays
let wait_time = 0;
function wait(delay, message) {
// Each "wait" call is adding its delay to the global wait_time
wait_time += delay
// This is the delay to use in this timeout
// "let" making it scoped to this function call
let timeoutDelay = wait_time;
console.log(timeoutDelay)
// Set a timeout
setTimeout(function() {
// If there is a message, use it on the title.
// else, redirect
if (message) {
console.log(message)
document.title = message;
} else {
window.location.href = ('https://example.com');
}
}, timeoutDelay)
}
<div id="changeText" style="font-family:verdana;"><br><br> Press ENTER to continue</div>

Where do I place my "document.getElementById("").innerHTML = "";" Within my Javascript?

At the moment I am creating an on screen timer in javascript. This is the code for my timer:
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function() {
console.log(i);
i = i - 1;
if (i < 0) {
clearInterval(countdownTimer);
}
}, 1000);
}
I am just wondering where I should place my document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
I am also wondering if the above document.getElementById is correct (will it be displayed as a onscreen timer or will it fail or something)?
Thanks in advanced.
Try this:
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function () {
console.log(i);
i = i - 1;
if (i < 0) {
clearInterval(countdownTimer);
return; //This will prevent -1 to be written to html
}
document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
}, 1000);
}
startTimer();
Dont forget to call the function.
Demo: http://jsfiddle.net/GCu2D/842/
You can put the
document.getElementById("time-remaining").innerHTML = "Time Remaining:" + i;
After the startTimer function or really anywhere.
And yes thedocument.getElementById is correct, if your html id is the same one as in javascript.

Set up a counter for a JavaScript timer loop based on number of images

What I would like to do is set each BannerImg element to display: none one at a time using a timer setup. Then, once I have looped through all BannerImg elements, I want to reset them to display: block. It's basically like a image rotator that I'm trying to make...but right now, I'm not sure how to target each BannerImg element one at a time--I am targeting them all at once, which is not what I want to do.
jQuery.noConflict();
(function($) {
$(document).ready(function() {
var BannerCount = $('BannerImg').length;
var intervalID = window.setInterval(function() {
$('.BannerImg').toggleClass("HideBannerImg");
}, 2000);
});
}(jQuery));
Use .eq(index). You'll probably want to cache your collection to make it faster:
(function($) {
$(document).ready(function() {
var $banners = $('.BannerImg');
var index = 0;
var intervalID = window.setInterval(function() {
$banners.eq(index).toggleClass("HideBannerImg");
index++;
// Check to see if we've hit the end of the collection
// If so, stop the interval.
if (index === $banners.length) {
clearInterval(intervalID);
}
}, 2000);
});
}(jQuery));
I'm kind of guessing you want something like this (correct me if I'm wrong):
setInterval(function () {
if ($('.BannerImg').last().hasClass('HideBannerImg')) {
$('.HideBannerImg').first().removeClass('HideBannerImg');
} else {
$('.BannerImg').not('.HideBannerImg').first().addClass('HideBannerImg');
}
}, 1000);
jQuery.noConflict();
(function($) {
$(document).ready(function() {
var iterator = 0;
var BannerCount = $('BannerImg').length;
var intervalID = window.setInterval(function() {
$('.BannerImg').eq(iterator).toggleClass("HideBannerImg");
iterator += 1;
if (iterator === BannerCount.length - 1) {
clearInterval(intervalID);
$('.BannerImg').removeClass("HideBannerImg");
}
}, 2000);
});
}(jQuery));
try this recursive function
var images = $('.BannerImg').each();
var hideImage = function(index){
images[index].toggleClass("HideBannerImg");
if(index < images.length-1)
setTimeout(function(){
hideImage(index++);
}, 2000);
}
hideImage(0);
After calling $('.BannerImg') you need to use jQuery's each to loop over each of the elements it selected.
jQuery.noConflict();
(function($) {
$(document).ready(function() {
$('.BannerImg').each(function() {
var $this = $(this);
var intervalID = window.setInterval(function() {
$this.toggleClass("HideBannerImg");
}, 2000);
});
});
}(jQuery));
Just note that this will toggle on and off over and over until you clear the interval.

Is there any way to start a setInterval one second after another?

http://jsfiddle.net/9DP2d/
setInterval(toggleredBox, 1000);
setInterval(toggleorangeBox, 1000);
setInterval(toggleyellowBox, 1000);
var toggleredBox = function toggleredBox() {
$(".redBox").slideToggle(1000);
};
var toggleorangeBox = function toggleorangeBox() {
$(".orangeBox").slideToggle(1000);
};
var toggleyellowBox = function toggleyellowBox() {
$(".yellowBox").slideToggle(1000);
};
So the problem is that all 3 boxes are firing all at once: is there any way to get them to go one after another simultaneously?
Can do it like this:
setInterval(toggleredBox, 3000);
var toggleredBox = function toggleredBox() {
$(".redBox").slideToggle(1000);
setTimeout(toggleorangeBox, 1000);
};
var toggleorangeBox = function toggleorangeBox() {
$(".orangeBox").slideToggle(1000);
setTimeout(toggleyellowBox, 1000);
};
var toggleyellowBox = function toggleyellowBox() {
$(".yellowBox").slideToggle(1000);
};
Can also have another setTimeout in the last function and simply call the function where you want the animation to start.
fiddle
You can use setTimeout do delay the start:
setInterval(toggleredBox, 1000);
setTimeout(function(){
setInterval(toggleorangeBox, 1000);
}, 1000):
setTimeout(function(){
setInterval(toggleyellowBox, 1000);
}, 2000):
You can also use a single interval for all three, and use a counter to check when to toggle them the first time:
setInterval(toggleBoxes, 1000);
var cnt = 0;
function toggleBoxes() {
$(".redBox").slideToggle(1000);
if (cnt > 0) $(".orangeBox").slideToggle(1000);
if (cnt > 1) $(".yellowBox").slideToggle(1000);
cnt++;
};
Demo: http://jsfiddle.net/9DP2d/2/
To try to implement the "one after the other simultaneously" (whatever that means):
setInterval(toggleredBox, 1000);
var toggleredBox = function() {
$(".redBox").slideToggle(1000, toggleorangeBox);
};
var toggleorangeBox = function() {
$(".orangeBox").slideToggle(1000, toggleyellowBox);
};
var toggleyellowBox = function() {
$(".yellowBox").slideToggle(1000);
};

jQuery: Stop and start "setInterval"

I have a slideshow on my website but there is a problem with in.
Here, my JS:
var size_ini = 1;
$(document).ready(function() {
setInterval('$("#next").click()',10000)
$("#next").click(function() {
if(size_ini < 3);
size_ini++;
else
size_ini = 1
$(".sample").hide();
$("#id" + size_ini).show();
$(".comment" + size_ini).show();
$(".comment_description" + size_ini).show();
});
$("#prev").click(function() {
if(size_ini > 1)
size_ini--;
else
size_ini = 3;
$(".sample").hide();
$("#id" + size_ini).show();
$(".comment" + size_ini).show();
$(".comment_description" + size_ini).show();
});
});
As you can see I have a Timer of 10 sec. for slide. I have a previous and a next button. So when i clicked on one of the button the timer should stop and starts again. I have tried "clearInterval" but this doesn't work.
Can anyone tell how this works.
Here is FIDDLE.
Fiddle Demo
var size_ini = 1;
$(document).ready(function () {
var timer = setInterval('$("#next").click()', 10000); //assign timer to a variable
$("#next").click(function () {
if (size_ini < 3) size_ini++;
else size_ini = 1
$(".sample").hide();
$("#id" + size_ini).show();
clearInterval(timer); //clear interval
timer = setInterval('$("#next").click()', 10000); //start it again
});
$("#prev").click(function () {
if (size_ini > 1) size_ini--;
else size_ini = 3;
$(".sample").hide();
$("#id" + size_ini).show();
clearInterval(timer); //clear interval
timer = setInterval('$("#next").click()', 10000); //start it again
});
});
If you're going to want to clear the interval you need to assign it to a variable, then you can clear it easily -
var myInterval = setInterval('$("#next").click()',10000);
Then clear like this -
clearInterval(myInterval);
Once the interval has been cleared make sure to reset it and assign it to a variable again if you want it to continue.
<button id="start">Start</button>
<button id="stop">Stop</button>
var timer;
$("#start").click(function() {
timer = setInterval(function(){$("#next").trigger("click");},"500");
});
$("#stop").click(function() {
clearInterval(timer);
});

Categories

Resources