Refresh function per 3 seconds - javascript

function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "This is text1."
myimages[2] = "This is text2."
myimages[3] = "This is text3."
myimages[4] = "This is text4."
myimages[5] = "This is text5."
myimages[6] = "This is text6."
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.write('<h1 class="comingsoon">' + myimages[ry] + '</h1>')
}
random_imglink()
How do you make it so that the above code gets refreshed every 3 seconds? Like, the output is refreshed every 3 seconds. Thanks.

setInterval is easier way for your query.
Simple Example:
setInterval(function(){ alert("Hello"); }, 3000);

Don't use document.write. Use document.innerHTML instead.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
And of course the setInterval, as the other answers suggest.

I've created a fiddle that I think does what you want.
I hope you like cats.
http://jsfiddle.net/alexjamesbrown/9cu5L666/
Note - I'm setting the inner html of a div, rather than the whole document
function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "http://placekitten.com/g/100/400"
myimages[2] = "http://placekitten.com/g/200/250"
myimages[3] = "http://placekitten.com/g/300/234"
myimages[4] = "http://placekitten.com/g/500/300"
myimages[5] = "http://placekitten.com/g/100/400"
myimages[6] = "http://placekitten.com/g/430/100"
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1;
var div = document.getElementById('myContainer');
div.innerHTML='<h1 class="comingsoon"><img src="' + myimages[ry] + '"</img></h1>'
}
setInterval(function(){ random_imglink(); }, 3000);

You can use setInterval
window.setInterval(random_imglink,3000);

You can use
window.setInterval(random_imglink, 3000);
but be cautious because if your browser does not render the content in the time interval you should expect choppiness and dropped frames. A much better approach is to use requestAnimationFrame
The Window.requestAnimationFrame() method tells the browser that you
wish to perform an animation and requests that the browser call a
specified function to update an animation before the next repaint. The
method takes as an argument a callback to be invoked before the
repaint.
function random_imglink() {
var myimages = new Array()
//specify random images below. You can have as many as you wish
myimages[1] = "This is text1."
myimages[2] = "This is text2."
myimages[3] = "This is text3."
myimages[4] = "This is text4."
myimages[5] = "This is text5."
myimages[6] = "This is text6."
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.body.innerHTML = '<h1 class="comingsoon">' + myimages[ry] + '</h1>';
}
window.setInterval(random_imglink, 3000);

Related

Put links in images that are located in <script>

I'm new to html, and I also have no idea how to work with js, so can I insert a link in multiple images inside of javascript of an html?
Here is a code that make the image change every time I refresh,
What I need to do is make these image clickable, and leading to another site
Preferably, I'd want to try to make it so that the js can lead to a code in html, so i can also add stuff such as height
<img src="3w.png" alt="car" height="333">
function random_imglink() {
var myimages = new Array()
myimages[1] = "1.png"
myimages[2] = "2.png"
myimages[3] = "3w.png"
myimages[4] = "4w.png"
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.write('<img src="' + myimages[ry] + '" border=0>')
}
random_imglink()
Arrays are 0 based so no need to force 1 when 0
Just change the HTML to be a link
It is recommended to not use document.write, so instead insert it into a container
I am using template literals to create the link and eventListener to see when the page has loaded
const myimages = ["1.png", "2.png", "3w.png", "4w.png"]
const links = ["page1.html","page2.html","page3.html","page4.html"];
function random_imglink() {
var ry = Math.floor(Math.random() * myimages.length)
return `<img src="${myimages[ry]}" height="333" border=0/>`;
}
window.addEventListener("DOMContentLoaded", function() {
document.getElementById("linkContainer").innerHTML = random_imglink();
});
<div id="linkContainer"></div>

How to make images appear randomly in Javascript?

I need to create a web page with a button that says "start game". When this button is clicked, 5 images I have downloaded (img1.png...img5.png) must appear randomly, one at a time, every half a second. Here is my code so far, any help would be greatly appreciated!
<html>
<head>
<script>
var rollImagesSchedule;
var rollImagesCounter;
function rollImagesAnimation(){
rollImagesCounter = 0;
rollImagesSchedule = setInterval(500);
}
function rollImages(){
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
rollImagesCounter = rollImagesCounter + 1;
if (rollImagesCounter == 10){
clearInterval(rollImagesSchedule);
}
}
</script>
</head>
<body>
<h1>Game</h1>
<button onClick="rollImagesAnimation()">Start frog game</button>
<br /><br />
<img id="display" style='width:200px; height:200px;'>
</body>
</html>
I think you're getting stuck with the way to use setInterval.
You can try to create a counter outside setInterval function, and nest all of your works inside of it. And the counter should be checked at the top.
function rollImages(){
var counter = 0;
var interval = setInterval(function () {
if (counter === 10) {
clearInterval(interval);
return;
}
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
counter++;
}, 500);
}
Then, you can edit the way to catch event rollImages:
<button onClick="rollImages()">Start frog game</button>
My English is not very good, so I might misunderstand your question. Let me answer it according to what I understand.
Your requirement is to randomly display one of the five pictures every 500 milliseconds, right? If so, you can try this idea:
Put the src of 5 pictures into an array
var imageSrcs = ["image1","image2","image3","image4","image5"];
Every 500 milliseconds, execute the following function:
function rollImages(){
// Randomly generate a random number between 0-4
int index = Math.floor(Math.random() * 5) + 1;
var theImage = document.getElementById("display");
// Use random numbers as subscripts and take values from the array
theImage.src = imageSrcs[index];
}
You can store the images name files into an array and then setInterval a random number and assign the source of an img html element:
var list = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
var i = 0;
function changeImgs() {
var imageValue = Math.floor(Math.random() * list.length - 1) + 1;
image.src = list[imageValue];
}
setInterval(function() {
changeImgs()
}, 2000);
window.onload = changeImgs;
<img id="image" class="size">

Javascript 'Dot Dot Dot' While Calculating

I have a function to display dot dot dot in a popup window while generating a report. I want to display the text:
Generating Report.
Generating Report..
Generating Report...
...repeat, until the report is ready. So far I've only been able to get the three dots in the popup without the other text. Here is my code snippet:
on(link, "click", function(){
var dots = window.setInterval( function() {
var wait = document.getElementById("reportLink");
if ( wait.innerHTML.length > 2)
wait.innerHTML = "";
else
wait.innerHTML += ".";
}, 400);
domAttr.set(dom.byId("reportLink"), "innerHTML", dots);
I tried this but it didn't work:
domAttr.set(dom.byId("reportLink"), "innerHTML", "Generating Report" + dots);
The function you're passing to setInterval is directly manipulating the dom element instead of returning a value (which wouldn't work anyway), so you "Generating Report" + dots won't work since dots is just a reference to the setInterval function. Instead, you need to modify your setInterval function using something like this (untested since I'm not sure what JS library/framework you're using):
var dots = window.setInterval( function() {
var wait = document.getElementById("reportLink"),
msg = "Generating Report",
msgLen = msg.length;
// Initialize to msg if blank
wait.innerHTML = (wait.innerHTML === "")
? msg
: wait.innerHTML;
if (wait.innerHTML.length >= (msgLen + 2))
wait.innerHTML = msg;
else
wait.innerHTML += ".";
}, 400);
Instead of initializing and testing your message by empty string, this uses the actual message you want to show. I also made the number of dots configurable by variable instead of using a "magic number".
[EDIT 1]
Make sure you remove this line (and any derivatives):
domAttr.set(dom.byId("reportLink"), "innerHTML", dots);
The function you're passing to setInterval is doing all the work.
[EDIT 2: Fixed the excessive dots on first run by initializing to msg if the reportLink element is empty.]
Try this:
var dots = window.setInterval( function() {
var wait = document.getElementById("reportLink");
if ( wait.innerHTML.length > 19)
wait.innerHTML = "";
else
wait.innerHTML += ".";
}, 400);
var text = "Generating Report" + dots;
domAttr.set(dom.byId("reportLink"), "innerHTML", text);
When you check the length you need to include the length of 'Generating report'.
maybe this?
var wait = document.getElementById("reportLink");
var loop = 0;
var text = "Generating Report";
window.setInterval( function() {
if ( loop > 2) {
wait.innerHTML = text;
loop = 0
} else {
wait.innerHTML += ".";
loop++
}
}, 400);

Do/while loop not counting number of rolls or lining up with dice

I'm just learning javascript and my project is to create a web page with the following elements: An h2 header, two img elements, an input box, and a button element. When the page loads, Dice.getURL is called twice to get the URL for the 1-dot die, and the jQuery.attr() function is used to display the images when the page loads: When the user enters a target number and clicks Roll 'em!, the images are updated die-namically and the results displayed in a div on the page.
I've got the basics down but I have no idea how to do the rest of this stuff. I've been looking online but haven't found what I needed. I hope you guys can be what I need:
The main issue that I have is that the numRolls variable is not keep track of how many times the do/while loop runs through. I am also confused on how to keep track of the dice rolls via images so it displays the correct output when the "solution is found"
Here is a link to my jsfiddle: https://jsfiddle.net/0088v6nt/3/
HTML
<!Doctype html>
<body>
<h2>Roll Number</h2>
<img id="dice1" src="http://www.dave-reed.com/book3e/Images/die1.gif">
<img id="dice2" src="http://www.dave-reed.com/book3e/Images/die1.gif">
<p>Enter target number:</p>
<input type="text" id="num"><br><br>
<button id="R">Roll 'em!</button>
<br><br>
<div id="time"></div>
</body>
JavaScript
//define a Dice object, properties and methods
var Dice = {
sides: 6,
rollDie: function(diceElement) {
var rolledValue = Math.floor(Math.random() * this.sides) + 1;
var diceImage = this.getURL(rolledValue);
diceElement.attr("src", diceImage);
},
rollDice: function() {
var diceTotal = 0;
diceTotal += this.rollDie($('#dice1'));
diceTotal += this.rollDie($('#dice2'));
return diceTotal;
},
URL_prefix: "http://dave-reed.com/book3e/Images/",
getURL: function(n) {
//return the URL for an n-dot die
return this.URL_prefix + "die" + n + ".gif";
}
};
//top-level function
function roll_number(n) {
Dice.rollDice();
var die1 = 0;
var die2 = 0;
var numRolls = 0;
do {
die1 = Dice.rollDie($('#dice1'));
die2 = Dice.rollDie($('#dice2'));
numRolls++;
} while(die1 + die2 == n);
return numRolls;
//roll two dice until you hit n
//return the number of rolls
}
function getRoll () {
var number = parseFloat($("#num").val());
var numRolls = roll_number(number);
$("#time").text( "You rolled " + number + " in " + numRolls + " rolls");
}
$(document).ready(function(){
$("#R").on("click", getRoll);
//$("#roll").on("click", Dice.getURL);
});
Thank you again!
-Kron
There's two issues with your code. First die1 and die2 are never set because Dice.rollDie doesn't return a value. Updating the function to return the value of the die fixes this:
rollDie: function(diceElement) {
var rolledValue = Math.floor(Math.random() * this.sides) + 1;
var diceImage = this.getURL(rolledValue);
diceElement.attr("src", diceImage);
return rolledValue;
},
Second, the while loop currently only set to keep running while the sum matches the total, instead it should keep running while it doesn't match the total. It should look like instead:
while(die1 + die2 !== n);
This can lead to infinite loops if you pass a bad value to n (such as null, or anything greater than 12), so be careful
https://jsfiddle.net/0088v6nt/4/
You're setting the counter to zero every time the roll_number function is called i fixed it by moving the counter variable outside the function scope so it's not being reset all the time..
var numRolls = 0;
function roll_number(n) {
Dice.rollDice();
var die1 = 0;
var die2 = 0;
do {
die1 = Dice.rollDie($('#dice1'));
die2 = Dice.rollDie($('#dice2'));
numRolls++;
} while(die1 + die2 == n);
return numRolls;
//roll two dice until you hit n
//return the number of rolls
}
https://jsfiddle.net/0088v6nt/5/

Fading out in Javascript

Hey I'm new to javascript and I'm working on a small chat program right now.
I've got all the chatlogs (global& private and stuff..) but i want to add a button which can make (most of) the elements of these little 'clients' fade out and in, so that you dont have to see ALL of them at one time, just the ones you want.
The (relevant) code with the example element mess1:
h=0;
newroom = function (roomname) {
//create new container
var div = document.createElement('div');
div.className = 'container';
//new text input
var mess = document.createElement('input');
mess.type = 'text';
mess.id = 'mess1' + i;
div.appendChild(mess);
//minimizer button
var min = document.createElement('input');
min.type = 'button';
min.value = 'Minimize chat';
min.id = 'min' + i;
div.appendChild(min);
document.body.appendChild(div);
document.getElementById("min" + h).addEventListener("click", function (){
//this is where the magic happens
}
h++;
};
I've tried document.getElementById("mess1" + h).style.visibility = 'hidden';, but that just makes the element disappear, leaving a big ugly blank space behind.
I thought document.getElementById("mess1" + h).fadeOut('slow'); would fix that, but it just doesn't do anything...
Thanks in advance for your answers
function fadeout(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
first of all I will recommend to use jQuery, it will make your life much more easy. In jQuery, you can fade the element and then remove it like this
$("#mess1" + h).fadeOut('slow',function(){
$("#mess1" + h).remove();
});
It will first fade the element and will then remove it from node if required
You can use
document.getElementById("mess1" + h).style.display= 'none';
it will hide element without empty space. But if you whant to hide element with animation you can use eq. this jquery:
$("#mess1" + h).hide('slow')
or eq. 'fast' - as parameter

Categories