Javascript countdown timer to change image and link - javascript

Apologies in advance for being somewhat out of my depth here.
I am trying to use a JavaScript countdown timer on an ASP page to do the following - every sixty seconds after the a page loads, an image-based link will switch between one of five image/link combinations.
I've done something somewhat wrong here, and I can't find the problem. It never runs.
Thanks in advance for any assistance.
The images are named the following:
1_AdvoImg.gif 2_AdvoImg.gif 3_AdvoImg.gif 4_AdvoImg.gif 5_AdvoImg.gif
The urls are the following:
linkone.html linktwo.html linkthree.html linkfour.html linkfive.html
The html encapsulating the link is this:
<a id='AdvoLink' href='../'><img id='AdvoImg' src='' border="0"></a>
The javascript is this:
<script language="javascript">
function startTimer(duration) {
var timer = duration, seconds, imgprefix, imgname, linkurl;
imgprefix = 1;
setInterval(function () {
seconds = parseInt(timer % 60, 10);
imgname = imgprefix.concat("_AdvoImg.gif");
if (imgprefix == 1) {
linkurl = "linkone.html";
}
if (imgprefix == 2) {
linkurl = "linktwo.html";
}
if (imgprefix == 3) {
linkurl = "linkthree.html";
}
if (imgprefix == 4) {
linkurl = "linkfour.html";
}
if (imgprefix == 5) {
linkurl = "linkfive.html";
}
if (--timer <= 0) {
document.getElementById("AdvoLink").href = "";
document.getElementById("AdvoImg").src = imgname;
++imgprefix;
timer = duration;
}
}, 5);
}
window.onload = function () {
startTimer(60);
};
</script>

You are trying to build a timer inside a timer there.
Try keeping it as simple as possible.
What you actually need is just:
window.onload = function () {
setInterval(function () {
//your url changing magic here - without the timer stuff
}, 60000);
};
With this, your magic code should trigger every 60000 milliseconds => 60s => 1minute.
You could actually kinda "debug" it by using console.log() inside your loop.

dunno what you were using var seconds for so I removed it
edited to stop image number going over 5, change if loop to whatever number you need
function startTimer(duration) {
var timer = duration;var seconds;var imgprefix;var imgname;var linkurl;
imgprefix = 1;
setInterval(function() {
imgname = imgprefix+"_AdvoImg.gif";
if (imgprefix == 1) {
linkurl = "linkone.html";
}
if (imgprefix == 2) {
linkurl = "linktwo.html";
}
if (imgprefix == 3) {
linkurl = "linkthree.html";
}
if (imgprefix == 4) {
linkurl = "linkfour.html";
}
if (imgprefix == 5) {
linkurl = "linkfive.html";
}
document.getElementById("timer").innerHTML=timer;
timer--;
if (timer <= 0) {
document.getElementById("AdvoLink").href = linkurl;
document.getElementById("AdvoImg").src = imgname;
document.getElementById("result").innerHTML = "image src = "+imgname+" and href = "+linkurl;
if(imgprefix < 5){++imgprefix;}else{imgprefix =1;}
timer = duration;
}
}, 200//speed up and slow down here, in milliseconds
);
}
window.onload = function () {
startTimer(10);
};
<a id='AdvoLink' href='../'><img id='AdvoImg' src='' border="0"></a>
<div id="timer"> </div>
<div id='result'> </div>

Related

Restart Timer Using Javascript

I try to use JavaScript to set timer for my quiz.(setInterval) but if I finish the quiz earlier and click on start button gain, the time will start counting at the time I stop the quiz. How can I restart the time after I click on the start button again? .
<script>
var seconds = 40;
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") <= 0) {
var value = seconds;
alert(value);
} else {
var value = localStorage.getItem("counter");
}
} else {
var value = seconds;
}
document.getElementById("divCounter").innerHTML = value;
var counter = function() {
if (value <= 0) {
localStorage.setItem("counter", seconds);
value = seconds;
} else {
value = parseInt(value) - 1;
localStorage.setItem("counter", value);
}
document.getElementById("divCounter").innerHTML = value;
};
var interval = setInterval(function() { counter(); }, 1000);
</script>
Based on your current code what you need to do to reset the counter is set value=seconds and removing the current value in localStorage.
So assuming you have a button like this in your HTML:
<button type"button" onclick="resetCounter()">Reset</button>
you can add a resetCounter() function in your code:
var resetCounter = () => {
value = seconds;
localStorage.removeItem("counter");
};

Starting timer when clicking first card of memory game

Ok I am trying to wrap up a project and the only thing holding me back is it that they call for the timer to start on clicking a match game. The timer starts when the HTML file loads which is not what the project wants and I have tried some methods but ends up freezing the game. I want the timer to be able to start when clicking a card.
var open = [];
var matched = 0;
var moveCounter = 0;
var numStars = 3;
var timer = {
seconds: 0,
minutes: 0,
clearTime: -1
};
//Start timer
var startTimer = function () {
if (timer.seconds === 59) {
timer.minutes++;
timer.seconds = 0;
} else {
timer.seconds++;
};
// Ensure that single digit seconds are preceded with a 0
var formattedSec = "0";
if (timer.seconds < 10) {
formattedSec += timer.seconds
} else {
formattedSec = String(timer.seconds);
}
var time = String(timer.minutes) + ":" + formattedSec;
$(".timer").text(time);
};
This is the code for clicking on a card. I have tried to include a startTimer code into this but doesn't work.
var onClick = function() {
if (isValid( $(this) )) {
if (open.length === 0) {
openCard( $(this) );
} else if (open.length === 1) {
openCard( $(this) );
moveCounter++;
updateMoveCounter();
if (checkMatch()) {
setTimeout(setMatch, 300);
} else {
setTimeout(resetOpen, 700);
}
}
}
};
And this class code I use for my HTML file
<span class="timer">0:00</span>
Try this: https://codepen.io/anon/pen/boWQbe
All you needed to do was remove resetTimer() call from the function that happens on page load and then just do a check in the onClick (of card) to see if the timer has started yet. timer.seconds == 0 && timer.minutes == 0.

jQuery. How do I select live created element?

Here is the code:
helpers.ajaxModuleFormRequest('blockcallback', $(this), function() {
var timer = $('[data-timer]');
var seconds = timer.data('timer');
var interval = setInterval(function() {
if (seconds == 0) {
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
});
helper.ajaxModuleFormRequest() does an AJAX-request and then in $.ajax.done() method calls callback-function specified in 3rd param.
<div data-timer="20"></div> is inserted in DOM live $.ajax.done() method and I want to select it to start the timer. But the code doesn't work, $('[data-timer]').length returns 0. How can I fix this?
Here's a simplified example, which inserts a <div> dynamically and then starts the timer:
Html:
<html>
<head>Testpage</head>
<body></body>
</html>
JavaScript:
{
$('body').append('<div data-timer="20"></div>');
var timer = $('[data-timer]');
var seconds = timer.data('timer');
if (seconds!==undefined)
{
alert(seconds);
var interval = setInterval(function() {
if (seconds == 0) {
alert('elapsed!');
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
}
else
{
alert("Please specify a timer value!");
}
}
Note that initially the <div> is not there, it is inserted dynamically via
$('body').append('<div data-timer="20"></div>');
If you want to test whether it tests correctly for existance of the timer value, comment the line above, i.e.
// $('body').append('<div data-timer="20"></div>');
and you'll get the alert message "Please specify a timer value!".
Try it on jsfiddle:
jsfiddle
{
$('body').append('<div data-timer="20"></div>');
var timer = $('[data-timer]');
var seconds = timer.data('timer');
if (seconds!==undefined)
{
alert(seconds);
var interval = setInterval(function() {
if (seconds == 0) {
alert('elapsed!');
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
}
else
{
alert("Please specify a timer value!");
}
}
<head>Testpage</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The javascript for the time increases it's speed on the second loop

Help me debug this code. The button should open a link onclick and the visit button on the main page will be disabled and it's value will become a timer. There's no problem on first click, but when the timer runs out and I click the button again, the speed of the clock increases. Please help me.
<html>
<head>
<script type = "text/javascript">
var t;
var isTimeron = false;
var counter = 0;
function disableButt()
{
document.getElementById("but1").disabled = true;
}
function enableVisit()
{
document.getElementById("but1").disabled = false;
}
function stopMe()
{
isTimeron = false;
clearTimeout(t);
}
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
}
t = setTimeout("countdown();", 1000);
}
function startMe() {
if (!isTimeron)
{
counter = 10;
isTimeron = true;
countdown();
}
}
</script>
<body>
<a href='' target = '_blank'><input type = "button" id = "but1" value = "VISIT" style="background:#83FF59; font-weight:bold;"
onclick = "startMe(); disableButt();"/></a>
</body>
</html>
You are not stopping the first timer.
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
}
t = setTimeout("countdown();", 1000);
}
The counter goes under zero, you call stopMe() by you still call setTimeout. You have two timer going on now.
Just change it to
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
return;
}
t = setTimeout("countdown();", 1000);
}
Small suggestion avoid strings in setTimeout.
setTimout(countdown, 1000);
is better

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