How to add different timers for specific images? - javascript

I've been working on this traffic light code for a few weeks now and I have finally made it work automatically with a set timer. However, now I want to make it more realistic by giving each image in my array a specific time so e.g. green light is viewed for 5 seconds, yellow for 3 and so on.
Current code:
var list = ["only red1.jpg","red-yellow 2.jpg", "green3.jpg","yellowonly4.jpg"];
var nextlight = 0;
var timer;
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
firstlight.src = list[nextlight];
}
timer = setInterval(ChangeLight,1000);
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Code</h1>
<p>Traffic Light</p>
<img id="traffic" src="only red1.jpg">
<button type="button" onclick="ChangeLight()">Change Light</button>
</body>
</html>
I'm a javascript newbie so please no over complicated code and thank you for any help.

You need to change the data structure, persist delay with image src to set and use setTimeout instead of setInterval to schedule the execution on function recursively with delay.
var list = [{
src: "only red1.jpg",
interval: 10000
}, {
src: "red-yellow 2.jpg",
interval: 5000
}, {
src: "green3.jpg",
interval: 3000
}, {
src: "yellowonly4.jpg",
interval: 1000
}];
var nextlight = 0;
var timer;
function ChangeLight() {
var firstlight = document.getElementById('traffic');
var obj = list[nextlight];
firstlight.src = obj.src;
firstlight.alt = obj.src;
timer = setTimeout(ChangeLight, obj.interval);
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
}
ChangeLight();
<h1>JavaScript Code</h1>
<p>Traffic Light</p>
<img id="traffic" src="only red1.jpg">
<button type="button" onclick="ChangeLight()">Change Light</button>

You can change your lights to objects, and include a timer in them.
var list = [
{
img: "only red1.jpg",
timer: 1000
},
{
img: "red-yellow 2.jpg",
timer: 2000
},
{
img: "green3.jpg",
timer: 3000
},
{
img: "yellowonly4.jpg",
timer: 4000
}
];
var nextlight = 0;
var timer;
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
var light = list[nextlight];
console.log(light.img + ' lit for ' + light.timer + ' ms');
setTimeout(ChangeLight, light.timer);
//firstlight.src = list[nextlight];
}
ChangeLight();

Use setTimeout instead of setInterval and in handler function, change the value of duration based on current signal
var list = ["only red1.jpg", "red-yellow 2.jpg", "green3.jpg", "yellowonly4.jpg"];
var nextlight = 0;
var elem = document.getElementById('result');
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
firstlight.src = list[nextlight];
elem.textContent = list[nextlight];
var setTimeoutDuration = 0;
if (list[nextlight].indexOf('green') > -1) {
setTimeoutDuration = 5;
} else if (list[nextlight].indexOf('yellow') > -1) {
setTimeoutDuration = 3;
} else if (list[nextlight].indexOf('red') > -1) {
setTimeoutDuration = 2;
} else {
setTimeoutDuration = 1;
}
setTimeout(ChangeLight, setTimeoutDuration * 1000);
}
<h1>JavaScript Code</h1>
<p>Traffic Light</p>
<img id="traffic" src="only red1.jpg">
<div id="result"></div>
<button type="button" onclick="ChangeLight()">Change Light</button>

Make the array a 2D with filename and time duration.
In the function, use setTimeout to invoke itself in the time duration taken from the array.
Check the code. (Set an ALT attribute to show you the change).
var list = [["only red1.jpg",3],["red-yellow 2.jpg",4],[ "green3.jpg",5],["yellowonly4.jpg",6]];
var nextlight = 0;
var timer;
function ChangeLight() {
nextlight = nextlight + 1;
if (nextlight == list.length)
nextlight = 0;
var firstlight = document.getElementById('traffic');
firstlight.src = list[nextlight][0];
firstlight.setAttribute('alt',list[nextlight][0]);
setTimeout(ChangeLight,list[nextlight][1]*1000);
}
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Code</h1>
<p>Traffic Light</p>
<img id="traffic" src="only red1.jpg">
<button type="button" onclick="ChangeLight()">Change Light</button>
</body>
</html>

Related

How to make value become 0 in textbox?

I am making a dice game where you roll dice. When you roll a number that number adds to your total score. But when you roll a 1 you lose your total score and it switches to the other player. You can also hold to switch player.
As it is right now it become 0 after getting a 1 the first time. My problem is that when you switch back to the original starter player the score that was there before comes back. Like it does not stay the value of 0 but only looks like it.
var swithcing = false;
var current1 = 0;
var total1 = 0;
var current2 = 0;
var total2 = 0;
function roll() {
var randomnumber = Math.floor(Math.random() * 6) + 1;
var player1score = document.querySelector('.player1total');
var player1curent = document.querySelector('.player1');
var player2score = document.querySelector('.player2total')
var player2curent = document.querySelector('.player2')
if (randomnumber == 1) {
swithcing = !swithcing;
player1score.innerHTML = 0;
player1curent.innerHTML = 0;
player2curent.innerHTML = 0;
}
if (randomnumber == 1 && swithcing == false) {
player2score.innerHTML = 0;
}
if (swithcing == true) {
current2 += randomnumber;
player2score.innerHTML = current2;
player2curent.innerHTML = randomnumber;
}
if (swithcing == false) {
current1 += randomnumber;
player1score.innerHTML = current1;
player1curent.innerHTML = randomnumber;
}
}
function hold() {
swithcing = !swithcing;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />
I think your code should look something like this
let switching = false;
let current1 = 0;
let total1 = 0;
let current2 = 0;
let total2 = 0;
let randomnumber = 0
const player1score = document.querySelector('.player1total');
const player1current = document.querySelector('.player1');
const player2score = document.querySelector('.player2total');
const player2current = document.querySelector('.player2');
function roll() {
randomnumber = Math.floor(Math.random() * 6) + 1;
//console.log(randomnumber);
//logic for normal rolls
if(randomnumber > 1){
if(switching==true){
current2=randomnumber;//set to number rolled
total2+=randomnumber;//sum to total score
} else {
current1=randomnumber;//set to number rolled
total1+=randomnumber;//sum to total score
}
}
//logic if player loses
if (randomnumber == 1) {
//switch
switching = !switching;
//if switches to player 2
current1=0;//reset
current2=0;//reset
if(switching==true){
//console.log("Player 2 selected");
total2+=total1//total becomes player 1 previous total
total1=0;//player 1 total resets
} else {
//console.log("Player 1 selected");
total1+=total2//total becomes player 2 previous total
total2=0;//player 2 total resets
}
}
player1score.textContent = total1;
player1current.textContent = current1;
player2current.textContent = current2;
player2score.textContent = total2;
}
function hold() {
switching = !switching;
player1score.textContent = total1;
player1current.textContent = 0;
player2current.textContent = 0;
player2score.textContent = total2;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />

It doesn't move to the next image

I am trying to create a slideshow. I have created two buttons because I want to do it in two ways. One way is when I press the next button to move to the next image(single image movement) and when I press the slideshow button to make it move along with not pressing a button. I didn't manage to fix it. Please help me if you can.
var img = new Array();
img[0] = "https://images-na.ssl-images-amazon.com/images/I/5101NtSnx0L._AC_.jpg";
img[1] = "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5ecc17cdfd6d6700060f826c%2F0x0.jpg";
img[2] = "https://cdn.episode.ninja/file/episodeninja/4090819.jpg";
img[3] = "https://i.pinimg.com/564x/f0/e5/a9/f0e5a984f263b7ecb5c9cd26a493a115.jpg";
function Next() {
if (i < img.length - 1)
i++;
else
i = 0;
document.getElementById("img1").src = img[i];
}
startslideshow() {
id = window.setInterval("Next()", 1000);
var x = document.getElementById("txt").value;
id2 = window.clearTimeout("Cancel()", x * 1000)
}
<body>
<img id="img1" height="300" width="300" src="https://2.bp.blogspot.com/-ho7KT0UEARE/VPbiU-U_KSI/AAAAAAAALVM/iZdcRS6KHvQ/s1600/Acrobatty%2BBunny%2B-%2BRobert%2BMcKimson%2B(3).jpg" /> <br>
<button id="Next" onclick="Next()"> Next </button>
<button onclick="startslideshow()">startSlideShow</button>
</body>
here is the solution that we have came up with
<body>
<img id="img1" height="300" width="300" src="https://2.bp.blogspot.com/-ho7KT0UEARE/VPbiU-U_KSI/AAAAAAAALVM/iZdcRS6KHvQ/s1600/Acrobatty%2BBunny%2B-%2BRobert%2BMcKimson%2B(3).jpg" /> <br>
<button id="Next" onclick="Next()"> Next </button>
<button onclick="startslideshow()">startSlideShow</button>
<button onclick="stopslideshow()">stopSlideShow</button>
</body>
var img = new Array();
var cur = 0;
var timer = null;
img[0] = "https://images-na.ssl-images-amazon.com/images/I/5101NtSnx0L._AC_.jpg";
img[1] = "https://thumbor.forbes.com/thumbor/fit-in/1200x0/filters%3Aformat%28jpg%29/https%3A%2F%2Fspecials-images.forbesimg.com%2Fimageserve%2F5ecc17cdfd6d6700060f826c%2F0x0.jpg";
img[2] = "https://cdn.episode.ninja/file/episodeninja/4090819.jpg";
img[3] = "https://i.pinimg.com/564x/f0/e5/a9/f0e5a984f263b7ecb5c9cd26a493a115.jpg";
function Next() {
cur = (cur < img.length - 1) ? cur + 1 : 0;
document.getElementById("img1").src = img[cur];
}
function startslideshow() {
timer = setInterval(function() {
Next();
}, 500);
}
function stopslideshow() {
if (timer) {
clearInterval(timer);
timer = null;
}
}

The image changes automatically - Start button

I wanted to add a button to start the change between images, to avoid the start of the change on its own
You must press the button until the change starts
var imageSources = ["https://www.w3schools.com/css/img_fjords.jpg", "https://www.w3schools.com/howto/img_mountains.jpg"]
var index = 0;
setInterval(function(){
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
}, 2000);
<img id="image" src="https://www.w3schools.com/css/img_fjords.jpg" style="width:300px">
Hi Please have a look I hope it's helpful Thanks
https://jsfiddle.net/sanat/xc5w8ngy/7/
<button id="start">
start
</button>
<button id="stop">
stop
</button>
<br>
<br>
<img id="image" src="https://www.w3schools.com/css/img_fjords.jpg" style="width:300px">
var myVar = '';
$(function(){
$("#start").on('click',function(){
var imageSources = ["https://www.w3schools.com/css/img_fjords.jpg", "https://www.w3schools.com/howto/img_mountains.jpg"]
var index = 0;
myVar = setInterval(function(){
if (index === imageSources.length) {
index = 0;
}
document.getElementById("image").src = imageSources[index];
index++;
}, 2000);
});
$("#stop").on('click',function(){
clearInterval(myVar);
});
});

How to decrement each click of the animation

I am trying to create animation game. Animation game must consits of One image alternating with another every half a second. I am intended to count++ on each click of the happy-face fish and count-- on each sad-face fish clicked. But, my code is only incrementing, whatever the image is clicked. Also,my code shows me two different images while It must have to be only one.
I have to count a click while my animation is running ( animation: images should be alternating every half a second. It will look like fish is smiling for half second and then crying for another half second then repeats). If i click on happy face, I will score 1 and if click on sad-face I will lose 1. In the end it must show you win if i achieve 10 and resets again on clicking Start Animation.
[Output should be like this:][1]
var image = "happy";
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
fish_img = document.getElementById("happy_fish");
f_img = document.getElementById("happy_fish");
fish_img.classList.add('on');
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
if (image == "happy") {
image = "sad";
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
} else {
image = "happy";
fish_img.src =
"https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
}
}
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="" id="sad_fish" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
I modified your StartAnimation and animationfunction methods to make the fish dissapear with a toggle instead of trying to modify the source of the image.
I made it with a css class off which will make a fish dissapear with display: none;
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
var initialWords = document.getElementById("d");
initialWords.innerHTML = "Your Score: <span id=\"score\">0</span>";
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
var fish_img = document.getElementById("happy_fish");
var f_img = document.getElementById("sad_fish");
fish_img.classList.toggle('off');
f_img.classList.toggle('off');
}
.off {
display: none;
}
<button onClick="StartAnimation()">Start Animation</button>
<br>
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="happy" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="sad" id="sad_fish" class="off" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
You can make things a lot simpler by having one img element and one click handler.
In the snippet I merged the two click handlers into one and added a check for the state of the fish (being represented now by the boolean isHappy).
I attached this handler to a single img element in your HTML and in the animation function I alternate its src attribute between the happy and sad fish according to the isHappy state.
Additionally, Since the counter and the total score are the same, I use only the total score variable.
var isHappy = true;
var totalscore;
var Schedule;
function clickFish() {
if (isHappy) {
totalscore++;
} else {
totalscore--;
}
var scoreSpan = document.getElementById("score");
scoreSpan.innerHTML = totalscore;
if (totalscore === 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + totalscore + " Game Over. You Win!";
}
}
function StartAnimation() {
isHappy = true
totalscore = 0;
clearInterval(Schedule);
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
fish_img = document.getElementById("fish");
isHappy = !isHappy;
if (isHappy) {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
} else {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
}
}
<button onclick="StartAnimation()">Start animation</button><br />
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="fish" onClick="clickFish()">
<br>
<h1 id="d">
Your Score:
<span id="score">0</span>
</h1>

Timer not accurate [duplicate]

This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 6 years ago.
I am building an activity timer, but the code I have is not working properly. The timer is going ~40% faster than real time. What's going wrong?
var sec = 00;
var min = 00;
var hr = 00;
var t;
var timer_is_on = 0;
function timedCount() {
if (min == 0) {
min = 1;
}
document.getElementById('seconds').value = sec;
document.getElementById('minutes').value = min;
$('.node-form .form-item:nth-child(4) input').val(min);
document.getElementById('hours').value = hr;
$('.node-form .form-item:nth-child(3) input').val(hr);
sec = sec + 1;
if (sec == 60) {
sec = 0;
min = min + 1;
if (min == 60) {
min = 1;
hr = hr + 1;
}
}
t = setTimeout("timedCount()", 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetCount() {
stopCount();
sec = 0;
min = 0;
hr = 0;
document.getElementById('hours').value = 00;
$('.node-form .form-item:nth-child(3) input').val('0');
document.getElementById('minutes').value = 00;
$('.node-form .form-item:nth-child(4) input').val('0');
document.getElementById('seconds').value = 00;
}
function putInTimelog() {
// Put hours
var hourItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-hours-0-value-", 0) === 0) {
hourItems.push(hourFields[i]);
}
}
var hourField = 'edit-field-timelog-hours-0-value-';
hourField = hourField.concat(hourItems.length);
document.getElementById(hourField).value = hr;
// Put minutes
var minuteItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-minutes-0-value-", 0) === 0) {
minuteItems.push(hourFields[i]);
}
}
var minuteField = 'edit-field-timelog-minutes-0-value-';
minuteField = minuteField.concat(minuteItems.length);
alert(minuteField);
alert((minuteField).length);
document.getElementById(minuteField).value = min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span class="timer-title"><strong>Activity timer</strong></span>h:
<input id="hours" readonly="readonly" size="2" type="text" /> m:
<input id="minutes" readonly="readonly" size="2" type="text" /> s:
<input id="seconds" readonly="readonly" size="2" type="text" /><span class="timer-buttons"><input onclick="doTimer()" type="button" value="Start" /> <input onclick="stopCount()" type="button" value="Stop" /> <input onclick="resetCount()" type="button" value="Reset" /> </span>
</form>
View on JSFiddle
clock.js is my repo that might help when used in conjunction with window.setInterval(). Working example included.
Add <script src="https://rack.pub/clock.min.js"></script> to your HTML then call clock.now --> 1462248501241 each time you want a time snapshot. You can add and subtract intuitively from there.
The actual js looks like:
var clock = (function() {
// object to expose as public properties and methods such as clock.now
var pub = {};
//clock.now
Object.defineProperty(pub, "now", {
get: function () {
return Date.now();
}
});
//API
return pub;
}());
var doc = document;
var el = doc.getElementById('output');
window.setInterval(function(){
/// call your function here
el.innerHTML = clock.what.time(clock.now);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rack.pub/clock.min.js"></script>
<h2 id='output'></h2>

Categories

Resources