Display diffrent image depending on timer - javascript

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

Related

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.

JS countdown timer - Pause function

Here's a simple countdown timer that counts from 9 down to 0.
The countdown works fine. But what if I want to pause it mid-flow and then restart from where it was paused?
I have tried (see code below) to interrupt the countdown, save the number it was at, and then restart the function from the new number. But the countdown goes haywire, and I can't see why. Any ideas?
PS. I could cut and paste a timer from elsewhere, but I'm doing this for the learning experience. I'm sure there are better ways to code a countdown timer in JS, but it's bugging me that I can't make THIS way work and think I must be missing something obvious.
Many thanks
var currentTimeInt = 10;
var minn = [];
var stop = 0;
// stop
function stopCounter() {
currentTime = document.getElementById('mins').textContent; // grabs the number of minutes at moment of pause.
stop = 1;
}
// restart
function restart() {
stop = 0;
currentTimeInt = parseInt(currentTime, 10); // converts that number into an integer we can use
document.getElementById("mins").innerHTML=currentTimeInt;
newMinutes(); // restarts the newMinutes function with the start time currentTimeInt set to the time the counter stopped at
}
function newMinutes() {
document.getElementById('mins').innerHTML= currentTimeInt; // displays the counter
for (aa = currentTimeInt-1; aa >= 0; aa--) {
minn.push(aa); // builds an array of numbers in descending order
document.getElementById('mins').innerHTML= minn[aa];
for (let bb=1; bb<=currentTimeInt; bb++) {
if (bb<currentTimeInt) {
setTimeout( function timer(){
if (stop == 0) { // checks if "stop!" has been clicked and returns false to stop the function if that is the case
document.getElementById('mins').innerHTML= minn[bb];
console.log(minn[bb]);
}
else {return false;}
}, bb*1000 );
}
}
}
console.log(currentTimeInt + " the end");
}
<span>Minutes: </span><span id= "mins"></span>
<button onclick="newMinutes()">Go!</button>
<button onclick="stopCounter()">Stop!</button>
<button onclick="restart()">Reset!</button>
You may try this as an example:
var timerId;
var counter;
function start() {
console.log('start');
if (!counter) {
reset();
} else {
loop();
}
}
function pause() {
console.log('pause');
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
function reset() {
console.log('reset');
pause();
counter = 10;
loop();
}
function loop() {
timerId = setInterval(function() {
if (0 >= counter) {
pause();
return;
}
console.log('counter', counter);
counter--;
}, 500);
}
<button onclick='start();'>Start</button>
<button onclick='pause();'>Pause</button>
<button onclick='reset();'>Reset</button>
Here is my little Countdown with START, PAUSE, RESUME, STOP & RESET features:
var jqcd_start_id = 'input#jqcd_start';
var jqcd_time_id = 'input#jqcd_time';
var jqcd_count_id = 'span#jqcd_count';
var jqcd_end_message = 'Time is up!';
var jqcd_countdown = '';
var jqcd_status = 'stopped';
var jqcd_current = '';
function jqcd(action){
if (action == 'start') {
if (jqcd_status == 'stopped') {
jqcd_updtv(jqcd_start_id, 'Pause');
jqcd_status = 'running';
jqcd_current = jqcd_countdown;
jqcd_updtt(jqcd_count_id, jqcd_countdown);
}
else if (jqcd_status == 'running') {
jqcd_updtv(jqcd_start_id, 'Resume');
jqcd_status = 'paused';
}
else if (jqcd_status == 'paused') {
jqcd_updtv(jqcd_start_id, 'Pause');
jqcd_status = 'running';
}
}
else if (action == 'stop') {
jqcd_updtv(jqcd_start_id, 'Start');
jqcd_status = 'stopped';
jqcd_updtt(jqcd_count_id, jqcd_end_message);
}
else if (action == 'reset') {
jqcd_updtv(jqcd_start_id, 'Start');
jqcd_status = 'stopped';
jqcd_updtt(jqcd_count_id, jqcd_countdown);
}
var a = jqcd_current.split(":");
var m = a[0];
var s = (a[1] - 1);
if (s < 0) {
if (parseInt(m) == 0) {
jqcd_updtv(jqcd_start_id, 'Start');
jqcd_status = 'stopped';
jqcd_updtt(jqcd_count_id, jqcd_end_message);
}
else {
m = m - 1;
s = 59;
}
}
if(s >= 0){
setTimeout(function(){
if (jqcd_status == 'running') {
m = (parseInt(m) < 10)? "0" + parseInt(m): m;
s = (parseInt(s) < 10)? "0" + parseInt(s): s;
jqcd_updtt(jqcd_count_id, m + ":" + s);
jqcd_current = m + ":" + s;
jqcd('');
}
}, 1000);
}
}
function jqcd_updtv(selector, value) {
if (selector != '') {
$(selector).val(value);
}
}
function jqcd_updtt(selector, value) {
if (selector != '') {
$(selector).text(value);
}
}
$(document).ready(function() {
jqcd_countdown = $(jqcd_time_id).val();
jqcd_updtt(jqcd_count_id, jqcd_countdown);
$(jqcd_time_id).keyup(function() {
jqcd_countdown = $(jqcd_time_id).val();
jqcd_updtt(jqcd_count_id, jqcd_countdown);
jqcd_updtv(jqcd_start_id, 'Start');
jqcd_status = 'stopped';
});
});
span#jqcd_count {
font-size: 20pt;
font-weight: bold;
}
input#jqcd_start,
input#jqcd_stop,
input#jqcd_reset {
font-size: 12pt;
font-weight: bold;
}
input#jqcd_start,
input#jqcd_stop,
input#jqcd_reset {
width: 100px;
}
span#jqcd_count {
font-family: "Lucida Console", Monaco, "Courier New", Courier, monospace !IMPORTANT;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="jqcd_count">00:30</span><br><br>
<input type="button" id="jqcd_start" value="Start" onClick="jqcd('start')" />
<input type="button" id="jqcd_stop" value="Stop" onClick="jqcd('stop')" />
<input type="button" id="jqcd_reset" value="Reset" onClick="jqcd('reset')" /><br><br>
<input type="text" id="jqcd_time" value="00:10" />
<br><br>
It is pretty simple to customize. The first four variables in the JavaScript code can be adapted to work with your specific HTML.
If you want an action to take place every second, add your lines of code inside of the "jqcd_updtt" function.
The CSS is completely optional, of course.
The Countdown start time is set dynamically by altering the value in the "jqcd_time" field. If, however, you want to set a static value for the Countdown starting point, you can alter the variables inside the "$(document).ready(function() {" function at the end of the JavaScript code.
PS.
This Countdown has no maximum limit for minutes or seconds
What about keeping it KISS!
let i = 9,j
function chrono(){
if (i>=0){
now.innerText = i--
}
}
<h1><div id="now">⏰ Ready!</div>
<button onclick="setInterval(function(){ chrono() }, 1000);this.style.display='none'">Start</button>
<button onclick="i=10">Reset</button>
<button onclick="j=i;i=-1">Pause</button>
<button onclick="i=j">Continue</button>
This is the most basic example ready to be expanded, mostly there is no clearInterval.
The KISS principle states that most systems work best if they are kept
simple rather than made complicated; therefore simplicity should be a
key goal in design and unnecessary complexity should be avoided.
https://en.wikipedia.org/wiki/KISS_principle
Therefore, js incrementation and setInterval seems easy but they hide complex things.
An other approach using date.now() that provide an accurate unix timestamp based on the system clock, and the web audio api for beeping.
i = Date.now();j=i+10000;z.innerText="Target #"+j
function d(){
if(now.innerText < j){
now.innerText = Date.now()
k(3,603,80)
}
if(now.innerText > j){
now.innerHTML = "<b>TIME TRAVEL COMPLETE!</b>"
k(8,728,100)
}
}
setInterval(function(){ d() }, 100)
a=new AudioContext()
function k(w,x,y){
v=a.createOscillator()
u=a.createGain()
v.connect(u)
v.frequency.value=x
v.type="square"
u.connect(a.destination)
u.gain.value=w*0.01
v.start(a.currentTime)
v.stop(a.currentTime+y*0.001)
}
EPOCH: <out id="now"></out><h6 id="z">
The first issue here is that currentTime isn't globally defined, so it can't be accessed from within restart. Just put var currentTime; at the start of your file.
But you have another serious breaking issue in that you're using setTimeout in a really awkward way. You're creating multiple timeouts all at once and giving them a delay based on their relation tocurrentTimeInt. This has two problems. For one the use of two for loops isn't very efficient and also seems redundant as your inner for loop is just going to count up to the currentTimeInt anyway.
Secondly, you never clear (and probably won't be able to clear) the timeouts. That means when you restart your timer after pausing if any timeouts hadn't yet been fired, then your program will run those and make the minutes jump back and forth between the old timeouts and the new ones you create after unpausing.
I know in your comment you said you wanted to get this to work because you basically did the whole thing yourself, but it may not be worth continuing down this road. After looking at it some I think fixing your program would require it to be restructured, or else require it to be hacked in a way that makes it pretty inefficient. And if you're someone who's just learning Javascript, it's probably better to just start over and do it the right way anyway.
Below is an example of a better way using setInterval rather than setTimeout, but feel free to just try and figure it out on your own.
(There are ways you can improve the functionality of the code below, but it should be enough to get you the general idea)
var startTimeInt = 10;
var currentTimeInt = startTimeInt;
var interval = undefined;
// start the timer
function startCounter() {
if(!interval){
document.getElementById('mins').innerHTML = currentTimeInt;
interval = setInterval(newNumber, 1000) // set an interval
}
}
// stop
function stopCounter() {
// clear the interval
clearInterval(interval)
interval = undefined;
}
// reset the timer
function resetCounter(){
currentTimeInt = startTimeInt;
document.getElementById('mins').innerHTML = currentTimeInt;
//stopCounter(); startCounter();
}
// change the time and handle end of time event
function newNumber(){
currentTimeInt--; // decrement the current time
document.getElementById('mins').innerHTML = currentTimeInt;
if(currentTimeInt == 0){
console.log("Done");
stopCounter();
}
}
<span>Minutes: </span><span id= "mins"></span>
<button onclick="startCounter()">Go!</button>
<button onclick="stopCounter()">Stop!</button>
<button onclick="resetCounter()">Reset!</button>
Here is a working Snippet..
var paused = false;
var started = false;
var stopped = true;
var currentCount = 0;
var running = false;
interval = 1000;
maxCount = 10;
function start() {
if (stopped){
started = true;
paused= false;
stopped = false;
currentCount = maxCount;
loop(); running = true;
return;
}
paused= false;
}
function pause() {
paused= true;
}
function stop(){
paused = false;
started = false;
stopped = true;
running = false;
currentCount = 0;
}
function update(item){
document.getElementById("status").innerHTML = item;
//console.log(item);
--currentCount;
if(currentCount < 0){stop()}
}
function reset() {
currentCount = maxCount;
document.getElementById("status").innerHTML = currentCount;
}
function loop(){
if (!stopped){
if (!paused){update(currentCount);}
setTimeout(function(){loop()}, interval)
}
}
<button onclick='start();'>Start</button>
<button onclick='pause();'>Pause</button>
<button onclick='reset();'>Reset</button>
<button onclick='stop();'>Stop</button>
<div id="status"></div>
for anyone who want to re-use the code, simply change the value of timer and the render function to fit your project
var timer= 10;
var intervalID
// pause/stop
function stopTimer() {
clearInterval(intervalID);
intervalID= null;
}
// restart
function restart() {
stopTimer();
timer= 10;
render();
// Go(); //Optional
}
// start/resume
function Go() {
if(intervalID){
//if interval already created previously, exit function
return
}
intervalID = setInterval(
() => {
if(timer< 1){
//escape from interval so that counter dont go below 0
return stopTimer();
}
timer--;
render();
}, 1000); //1000 milisecond == 1 second
}
function render(){
// it is ok to run render redundantly as it does not mutate the data
// feel free to change this to fit your needs
console.log(timer);
document.getElementById("mins").innerHTML=timer;
}
render() //render once on load
<span>Minutes: </span><span id= "mins"></span>
<button onclick="Go()">Go!</button>
<button onclick="stopTimer()">Stop!</button>
<button onclick="restart()">Reset!</button>

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

Image change onclick Javascript, can I add a timer to change as well?

Edit: is there anyway to have the interval only kick in if the user has not clicked? example: I set a interval of 20 seconds, but if the user had clicked the first image at 15 seconds, the next image only shows up for the remaining 5 seconds. I need a timer -or- a click but not both. Thanks!
So I have the javascript below that currently works onclick. Can it be modified to also add a timer? So if they don't click on the first image, I can set a timer to go to image 2.. then to image 3.. and so on. Thx for your efforts!
<img alt="" src="image1.gif" style="height: XXXpx; width: XXXpx" id="imgClickAndChange" onclick="changeImage()" />
<script language="javascript">
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "image1.gif")
{
document.getElementById("imgClickAndChange").src = "image2.gif";
}
else
{
document.getElementById("imgClickAndChange").src = "image3.gif";
}
}
</script>
You can use setInterval to call the changeImage function at intervals.
This should work:
<script language="javascript">
function changeImage() {
var img = document.getElementById("imgClickAndChange");
img.src = (img.src == 'image1.gif') ? 'image2.gif' : 'image3.gif';
}
// auto-trigger every 1 second, change 1000 as needed
setInterval(changeImage, 1000);
</script>
Note: Modified the code to make it smaller.
use setInterval
setInterval(function() { changeImage(); }, 3000);
Try using this snippet below it picks a random image after a set time -
<script type="text/javascript" language="javascript">
var intTimer=0;
function ImageRotate()
{
intTimer = self.setInterval("GenerateRandom()",3000);
}
function GenerateRandom()
{
var intNumber = 10;
var intRandom = 0;
intRandom = Math.floor(Math.random() * intNumber + 1);
document.getElementById("ImageRandom1").src =
"Pictures1/Image" + intRandom + ".JPG";
}
</script>
Put your images in to array and than with setInterval call your function like this
jsBin Demo
Edited! updated
var i = 0,
element = document.getElementById("imgClickAndChange"),
images = ["image1.gif", "image2.gif", "image3.gif"],
timer = setInterval(changeImage, 25000);
function changeImage() {
element.src = images[(i >= images.length) ? (i = 0) : i++];
}
element.addEventListener("click", function() {
changeImage();
clearInterval(timer);
timer = setInterval(changeImage, 25000);
}, false);

How to stop my javascript countdown?

How can I stop my javascript function when countdown = 0?
JS:
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
}, 1000);
});
HTML:
<b id="show-time">20</b>
For one thing remove those evals. They don't do anything.
Then all you have to do is clear the timer when it reaches zero.
$(function(){
var timer = setInterval(function() {
var timeCounter = parseInt($("b[id=show-time]").text());
$("b[id=show-time]").text(--timeCounter); // remove one
if(!timeCounter) clearInterval(timer);
}, 1000);
});
It is easy! When you call setInterval it return an ID, so you can destroy the interval later. To destroy it you must use clearInterval(id), and voilà!
It works like this:
// Activate timer
var iv = window.setInterval(...);
// Deactive timer
window.clearInterval(iv);
Also you should use parseInt() instead of eval():
$(function() {
// Read the start value once and store it in a variable
var timeCounter = parseInt( $("b[id=show-time]").text() );
// Active the counter
var iv = window.setInterval(function() {
// Decrement by one and write back into the document
$("b[id=show-time]").text(--timeCounter);
// Check if counter == 0 -> stop counting
if (0 == timeCounter) {
window.clearInterval(iv);
// ...do whatever else needs to be done when counter == 0 ..
}
}, 1000);
});
Example:
var i = 0,
pid = setInterval(function() {
if (++i > 10)
clearInterval(pid);
}, 1000);
Based on what you wanted for your code ...
$(function() {
var el = document.getElementById('show-time'),
pid = setInterval(function() {
// (s - i) coerces s to Number
var t = el.innerHTML - 1;
el.innerHTML = t;
if (t < 1)
clearInterval(pid);
}, 1000);
});
Keep in mind that JS won't be 100% accurate with its timing.
Pasted code below or see the fiddle: http://jsfiddle.net/raHrm/
<script type="text/javascript">
$(function(){
var settimmer = 0,
timeCounter = $("#show-time").html(),
updateTime = timeCounter;
(function countDown() {
timeCounter = $("#show-time").html();
updateTime = parseInt(timeCounter)-1;
$("#show-time").html(updateTime);
if ( updateTime ) {
setTimeout(countDown, 1000);
}
})();
});​
</script>
Set the timer to a variable, then use clearInterval in-order to stop the loop. As for catching the end, use a simple conditional:
$(function(){
var elem=$('strong[id="show-time"]'),settimmer=0,updateTime,t;
t=window.setInterval(function() {
updateTime=parseFloat(elem.html(),10)-1;
if(updateTime==0) {
window.clearInterval(t);
elem.html('Done!');
} else {
elem.html(updateTime);
}
},1000);
});
Then in the HTML:
<strong id="show-time">20</strong>
The <b> tag is depreciated, try to avoid using it. Also, there is no reason to eval() the HTML you are getting from the element; a simple parseFloat() works just fine.

Categories