How to add a timer for images in JavaScript? - javascript

I've been working on this code which displays the next traffic light when a button is pressed. Now I am trying to diplay the images in the array every 3 seconds. I have tried using setTimeOut in my code but my code juts stays on the first traffic light.
code:
EDIT(FIXED)
<!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>
<script>
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, 3000);
</script>
</body>
</html>

Solution:
timer = setInterval("ChangeLight", 3000);
Put it out of the function ^^

2 things:
It's supposed to be setInterval(ChangeLight, 3000);
timer is inside the ChangeLight function. You should move it outside.

You may want to change timer = setTimeout("ChangeLight", 3000); into timer = setTimeout(ChangeLight, 3000);.

Related

How do I display a given random array element every two seconds until it is stopped?

I am trying to make a program that randomly displays one of four defined emojis given in an array when the button is clicked and switches every two seconds continues to do so until the stop button is clicked. Note that I have not finished the stop function yet as I cannot work out why my randomEmoji function is not displaying anything. Thanks in advance :).
var display = document.getElementById("emojiDisplay");
var emojiList = ["🥳", "🤩", "👾", "😵"];
function randomEmoji() {
emojiDisplay.innerHTML = emojiList[Math.floor(Math.random() *
emojiList.length)];
setInterval(function() {
document.getElementById("emojiDiplay").innerHTML = emojiList[i++];
if (i == emojiList.length) i = 0;
}, 2000);
}
function stop() {
}
<button onclick=randomEmoji()>Display random emoji</button>
<button onclick=stop()>Stop</button>
</br>
</br>
<div id="emojiDisplay">
</div>
Based on your idea and your code, I’ve updated it and let it work (the stop function works, too). You can check the below demo:
var display = document.getElementById("emojiDisplay");
var emojiList = [ "🥳", "🤩", "👾", "😵" ];
var i = 0;
var timer;
function randomEmoji() {
clearInterval(timer);
// Call show Emoji to let it shows instanly.
showEmoji();
// Put showEmoji function to let it repeats
timer = setInterval(function() {
showEmoji();
}, 2000);
}
function showEmoji() {
i = Math.floor(Math.random() * emojiList.length);
emojiDisplay.innerHTML = emojiList[i];
}
function stop() {
// clear interval timer to let it stops
clearInterval(timer);
}
<!DOCTYPE html>
<html>
<head>
<title>EmojiRandomiser</title>
</head>
<body>
<button onclick=randomEmoji()>Display random emoji</button>
<button onclick=stop()>Stop</button>
<br>
<br>
<div id="emojiDisplay">
</div>
</body>
</html>

How do i loop my timed sequence for my program in JavaScript

I have made a program that displays a traffic light, the colour is changed when a button is pressed. I don't know how to add a timed sequence to this, can anybody help? My task is to allow the sequence to continue without any user input on a timer.
This is my original program
<!DOCTYPE html>
<html>
<body>
<h1>Task 3</h1>
<p>Traffic Light</p>
<img id="light" src="./assets/red.jpg">
<button type="button" onclick="changeLights()">Change</button>
<script>
var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src = list[index];
}
</script>
</body>
</html>
I looked at timing events and attempted to use the setTimeout() function but all this does is adds a delay after each time the button is pressed.
<!DOCTYPE html>
<html>
<body>
<h1>Task 3</h1>
<p>Traffic Light</p>
<img id="light" src="./assets/red.jpg">
<button onclick="setTimeout(changeLights, 3000);">Try it</button>
<script>
var list = ["./assets/red.jpg","./assets/redamber.jpg", "./assets/green.jpg","./assets/amber.jpg" ];
var index = 0;
function changeLights() {
index = index + 1;
if (index == list.length)
index = 0;
var image = document.getElementById('light');
image.src = list[index];
}
</script>
</body>
I am new to JavaScript and i wouldn't know where to start so i appreciate the help.
My task is to allow the sequence to continue without any user input on a timer.
You need to use setInterval(func|code, delay)
remove this line
<button onclick="setTimeout(changeLights, 3000);">Try it</button>
And add this in your scripts
setInterval(changeLights, 3000);
setInterval is used when ever you want to run a function infinitely after every n milliseconds.
You can try this
<button onclick="setInterval(changeLights, 3000);">Try it</button>
Maybe you mean to use setInterval() function instead of setTimeout().

How do I make a button disappear after a certain amount of clicks

I have a button is it possible to make it disappear if I click it say 5 times? need to know for a little project I'm working on!
any response is appreciated!
Use this Code
HTML:
<button type='button' id='button_test_clicks'>
Click me!
</button>
JavaScript:
(function(){
var counter=0; // counter clicks initialization
var button=document.getElementById('button_test_clicks'); //Our button
button.addEventListener("click",function(){ //add a click event to button
counter++; //incement the counter
console.log(a);
if(counter==5){
button.style.display = 'none'; //hide if the clicks reached to 5
}
});
})();
But whenever the page refresh happens counter sets to zero, to avoid refresh problems learn about localStorage in javascript.
Assign id to your button.
<Button id='myButton' onclick="myFunction()">
On every click of button, keep incrementing the counter (I think you know how to do it)
After the counter is reached,
document.getElementById("Your_button_id_here").style.visibility = "hidden";
<script>
var counter=0;
function myFunction() {
//increment counter
counter+=1;
if(counter>4)
document.getElementById("Your_button_id_here").style.visibility = "hidden"
}
</script>
However, I think disabling would be more proper:
document.getElementById("Your_button_id_here").disabled=true
You could have a simple script like this :
var nbClicks=0;
function btnOnClick(btn){
if(++nbClicks>5){btn.style.display='none';}
}
And use it like that :
<input type="button" onclick="btnOnClick(this)" value="Click me 6 times !">
On every click just increment a variable's value and after got desired number, hide it by css and js.
I made a small example with jQuery
var count = 0;
$("#b1").click(function() {
count++;
if (count >= 5) {
$("#b1").hide();
}
});
<html>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</header>
<body>
<button id="b1">5 Clicks</button>
</body>
</html>

new mail counter javascript

I am having some major problems with a javascript app I'm working on. I want my window to open to a closed envelope and then after five seconds to change to an open envelope with a little 1 counter in the corner of it. I want the counter to continue to move up every five seconds unless the envelope is clicked. If clicked I want the count to start over. So far I have only gotten my closed envelope showing up. I'm new and have no idea what I am doing wrong so any help would be awesome!
My html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="mail.js"></script>
</head>
<body>
<img id"closed" src="closed.png" onclick="resetTimer()">
<span id="counter"></span>
</body>
</html>
And my JavaScript:
window.onload = function(){
var counter = 0;
var timer = setInterval(
function(){
counter++;
document.getElementById("demo").firstChild.nodeValue = counter;
},
5000
);
function openEnvelope(){
var img = document.getElementById("picture");
if (counter > 1){
img.src = "open.png"
}
}
open = setTimeout("open()", 1000);
function resetTimer(){
clearInterval(timer);
}
}
You need to increment your counter and set the counter span to have that value :
var counter = 0;
//Create your timer (setTimeout will only run once, setInterval will start again once run.
//1000 = 1 second
var timer = setInterval(openEnvelope, 1000);
function openEnvelope() {
var img = document.getElementById("picture");
var counterSpan = document.getElementById("counter");
if (counter > 1) {
img.src = "open.png"
counterSpan.innerHTML = counter;
}
//Add 1 to Counter
counter++;
}
function resetTimer() {
clearInterval(timer);
counter = 0;
}
This will run your openEnvelope function every second, and if the counter value is more than 1 it will set the Img Source to be open.png and the counter span to have the counters value. On the click of the Envelope it will clear the timer and reset the counter.
And your HTML will become :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="mail.js"></script>
</head>
<body>
<img id"picture" src="closed.png" onclick="resetTimer()">
<span id="counter"></span>
</body>
</html>
Here is a working JSFiddle for your problem, try creating a blank page and copying the HTML straight into the <body> tag and the Javascript into <script></script> tags in the <head> of your page.

Write sequence of random numbers in javascript to paragraph

Really a newbie question but I can't seem to find the answer. I need to have this html file show a bunch of random numbers, separated by 1 second intervals. For some reason (maybe obvious) it is only showing me the last one unless I have 1 alert after each random number generated. How can I correct this?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var randomnumber
var message
function placePossibleWinner()
{
randomnumber=Math.floor(Math.random()*11);
message="Teste ";
message=message.concat(randomnumber.toString());
document.getElementById("WINNER").innerHTML=message;
//alert(".")
}
</script>
</head>
<body>
<script type="text/javascript">
function runDraw()
{
var i=1
alert("start")
while (i<20)
{
setTimeout("placePossibleWinner()",1000)
i++
}
}
</script>
<h1>H Draw</h1>
<p id="WINNER">Draw</p>
<p></p>
<button onclick="runDraw()">Get me winner!</button>
</body>
</html>
Thanks in advance for any answers/comments.
The problem is all your setTimeouts are being triggered at the same time. Adding alerts pauses the JavaScript execution, so you see each number. Without that, after 1 second, all 19 setTimeouts run (one after another) and you just see one number (the screen is updated so fast, you just see one).
Try using setInterval instead.
function runDraw() {
var i = 1;
var interval = setInterval(function(){
if(i < 20){
placePossibleWinner();
i++;
}
else{
clearInterval(interval);
}
}, 1000);
}​
This will run the function once every second, until i is 20, then it will clear the interval.
I believe you want setInterval instead. using setTimeout in a loop will just queue up 20 calls immediately and they will all fire at once 1 second later. Also, you are setting the innerHTML of the p which will overwrite any previous text.
function placePossibleWinner() {
// add a var here, implicit global
var randomnumber=Math.floor(Math.random()*11);
// add a var here, implicit global
message="Teste " + randomnumber + '\n'; // new line
document.getElementById("WINNER").innerHTML += message; // concat, don't assign
}
function runDraw() {
var counter = 1;
var intervalID = setInterval(function () {
if (counter < 20) {
placePossibleWinner();
counter++;
} else {
clearInterval(intervalID);
}
}, 1000);
}
You are resetting your message in your functions and you are calling placePossibleWinner() the wrong way... you want to use setInterval. Below is a modification of your html/javascript
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var randomnumber;
var message = "Teste ";
var timesCalled = 0;
var funtionPointer;
function placePossibleWinner()
{
timesCalled++;
randomnumber=Math.floor(Math.random()*11);
message=message.concat(randomnumber.toString());
document.getElementById("WINNER").innerHTML=message;
if (timesCalled > 20)
{
clearInterval(functionPointer);
}
}
</script>
</head>
<body>
<script type="text/javascript">
function runDraw()
{
var i=1
alert("start")
functionPointer = setInterval(placePossibleWinner,1000)
}
</script>
<h1>H Draw</h1>
<p id="WINNER">Draw</p>
<p></p>
<button onclick="runDraw()">Get me winner!</button>
</body>
</html>
To start with,
setTimeout("placePossibleWinner()",1000)
should be
setTimeout(placePossibleWinner,1000)
The parameter to setTimeput should be a reference to a function. See JavaScript,setTimeout

Categories