Java Script iframe src change links by order instead of random - javascript

I am trying change iframe src automatically with java script. But it's works in randomly. I want this works on by order and also change milliseconds to minutes..!
var pages=new Array();
pages[0]="http://www.virtusa.com";
pages[1]="https://www.listertechnologies.com/";
pages[2]="https://intellectdesign.com/";
var time=600000; // this is set in milliseconds
function pageChange() {
var rand=Math.floor(Math.random()*pages.length);
document.getElementById("frame").src=pages[rand];
setTimeout("pageChange()",time);
}
onload=pageChange;

var pages = new Array();
pages[0] = "http://www.virtusa.com";
pages[1] = "https://www.listertechnologies.com/";
pages[2] = "https://intellectdesign.com/";
var index = 0;
var minute = 60000;
var time = 10 * minute;
function pageChange() {
var rand = pages[index];
document.getElementById("frame").src = rand;
setTimeout(pageChange, time);
index = index == pages.length - 1 ? 0 : index + 1;
}
onload = pageChange;

Related

How do I cycle through multiple lines with a javascript letter randomiser?

Ok so I have this code for a JavaScript letter randomiser that works perfectly fine, i'm just having trouble figuring out how i'd get it to produce more than just one line while still keeping my code relatively efficient.
Ideally id like it to say something like this and then cycle back to the start:
Hi, my name is Yeet
this is my website
I like making cool stuff
take a look around :)
Any help would be greatly appreciated :)))
window.onload = function() {
var theLetters = "abcdefghijklmnopqrstuvwxyz#%&^+=-";
var cntnt = "Hi, my name is Yeet";
var speed = 20; // ms per frame
var increment = 2; // frames per step
var clen = cntnt.length;
var si = 0;
var stri = 0;
var block = "";
var fixed = "";
//Call self x times, whole function wrapped in setTimeout
(function rustle(i) {
setTimeout(function() {
if (--i) {
rustle(i);
}
nextFrame(i);
si = si + 1;
}, speed);
})(clen * increment + 1);
function nextFrame(pos) {
for (var i = 0; i < clen - stri; i++) {
var num = Math.floor(theLetters.length * Math.random());
//Get random letter
var letter = theLetters.charAt(num);
block = block + letter;
}
if (si == (increment - 1)) {
stri++;
}
if (si == increment) {
// Add a letter;
// every speed*10 ms
fixed = fixed + cntnt.charAt(stri - 1);
si = 0;
}
$("#output").html(fixed + block);
block = "";
}
};
Make cntnt an array
var cntnt = ["Hi, my name is Yeet", "This is my website", "I like making cool stuff", "take a look around :)"];
and use pos % cntnt.length as the array index.
fixed = fixed + cntnt[pos % cntnt.length].charAt(stri - 1);

2 random images but not the same one

I have this function that shows two random images picked from a folder. Is there any chance I can modify the code so that I won't have the same image twice as result?
Thanks in advance.
var theImages = new Array()
theImages[0] = 'img/dyptichs/f-1.jpg'
theImages[1] = 'img/dyptichs/f-2.jpg'
theImages[2] = 'img/dyptichs/f-3.jpg'
theImages[3] = 'img/dyptichs/f-4.jpg'
theImages[4] = 'img/dyptichs/f-5.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var WI1 = Math.round(Math.random()*(p-1));
var WI2 = Math.round(Math.random()*(p-2));
function showImage1(){
document.write('<img src="'+theImages[WI1]+'">');
}
function showImage2(){
document.write('<img src="'+theImages[WI2]+'">');
}
You can do something like this:
var WI1 = Math.round(Math.random()*(p-1));
var WI2 = Math.round(Math.random()*(p-1));
while (WI2 === WI1) {
WI2 = Math.round(Math.random()*(p-1));
}
We keep generating a new number until it's different from WI1, ensuring it is unique.
The way I'd personally handle that is to randomise the array and then just grab the first 2 entries. That way you still pick 2 at random, but you guarantee not to get the same 2.
var theImages = new Array()
theImages[0] = 'img/dyptichs/f-1.jpg'
theImages[1] = 'img/dyptichs/f-2.jpg'
theImages[2] = 'img/dyptichs/f-3.jpg'
theImages[3] = 'img/dyptichs/f-4.jpg'
theImages[4] = 'img/dyptichs/f-5.jpg'
var randomImages = theImages
.concat()
.sort(function () {
return Math.random() > 0.5
? 1
: -1;
})
.slice(0, 2);
function showImage1() {
document.write('<img src="' + randomImages[0] + '">');
}
function showImage2() {
document.write('<img src="' + randomImages[1] + '">');
}
Edit: including the original array for a complete solution
var WI1 = Math.floor(Math.random()*p);
var WI2 = Math.floor(Math.random()*(p-1));
if (WI2 >= WI1) {
WI2 += 1;
}
Use floor instead of round and subtract 1, because with round you get twice less chance to get first or last element.
The if trick is slightly better than a loop in this case, though the loop is easier to apply to a more complex case.

Display two images every X hours, Javascript

Below is a code I am running to display a pair of images each day. I have been unable to have it display the images randomly, but instead each day it selects the next image in the Array (not at random). Javascript is not my specialty and I have been unsuccessful in making it select a new random image in both arrays each day.
I have also been unsuccessful in making it select them every 12 hours instead of each day, which is what I would prefer it to do. It must display the same ones for every person who views it for that period, until the timer resets, if possible.
<script type="text/javascript"><!--
var imlocation = "https://s31.postimg.org/";
function ImageArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
function linkArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
image = new ImageArray(4);
image[0] = 'v85buoebv/Day2.png';
image[1] = 'djdl322kr/Evening2.png';
image[2] = 'arubcg423/Night2.png';
image[3] = 'xf9kiljm3/Morning2.png';
link = new linkArray(11);
link[0] = 'q4xda5xdn/CLOUDY.png';
link[1] = '7141ttkjf/Heavyrain.png';
link[2] = 'gzp0gatyz/lightrain.png';
link[3] = 'xc3njrxob/Medium_Rain.png';
link[4] = 'x0m770h8b/NO_WEATHER.png';
link[5] = 's38mlwf97/omgrain.png';
link[6] = 'btigj04l7/Special_Weather.png';
link[7] = 'b59m025vf/WEREALLGONNADIErain.png';
link[8] = 'ubmt38md7/Windy.png';
link[9] = 'x0m770h8b/NO_WEATHER.png';
link[10] = 'x0m770h8b/NO_WEATHER.png';
var currentdate = new Date();
var imagenumber = currentdate.getDay();
document.write('<div id="NOTICEME"><center><img src="' + imlocation + image[imagenumber] + '"><img src="' + imlocation + link[imagenumber] + '"></center><br><div id="mowords">[center][img]' + imlocation + image[imagenumber] + '[/img][img]' + imlocation + link[imagenumber] + '[/img][/center]</div></div>');
//--></script>
I used this code as a base to go on. But no matter how I toy with it, it won't give me a random image from the array. Also, the div ID "mowords" and "NOTICEME" is an ID I am using for CSS reasons that has nothing to do with this code.
Edit:
Maybe going for random is the wrong way to do this. Is there a way to make the link = new linkArray select the date (as in 1 - 31) and the image = new ImageArray select the day (as in 1 - 7) like it is currently doing? It will create variance and the illusion of randomness in the long run.
If you know your arrays' indices, and they are integers, then you can use the following to get a pseudo-random integer between min and max:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
Now, however, your approach has been giving you certain "consistency" in your results, i.e. each day of the week giving you a certain image on every page show.
If you wish to implement randomness into it, you won't get such consistent results, meaning that on every page show, the image will be random independent of the day of the week or time of day.
To address this issue, you can take several approaches:
Have a server-side scripting language define the images (random or not) and save the "daily"/12-hour preferences into a .json/.js file, which then can be read by the JavaScript running in the browser. With this approach you would probably set the "refresh" rate via adding Expires headers on the .js file handling the parsing of the configuration file created by your server-side script -> https://gtmetrix.com/add-expires-headers.html
The other approach is to redefine your image selection logic based on the current date/time. However, the obvious downfall to that, is that you rely on the date and time of the user's computer, which can't always be trusted, so you have to work around that.
I would advise to look into a server-side scripting solution - PHP/Perl would do fine for this purpose.
UPDATED:
Have not tested, but try this (as per your comments):
<script type="text/javascript"><!--
var imlocation = "https://s31.postimg.org/";
function ImageArray (n) {
this.length = n;
for (var i = 0; i <= n; i++) {
this[i] = ''
}
}
function linkArray (n) {
this.length = n;
for (var i = 0; i <= n; i++) {
this[i] = ''
}
}
image = new ImageArray(6);
image[0] = 'v85buoebv/Day2.png';
image[1] = 'djdl322kr/Evening2.png';
image[2] = 'arubcg423/Night2.png';
image[3] = 'xf9kiljm3/Morning2.png';
image[4] = '';
image[5] = '';
image[6] = '';
link = new linkArray(30);
link[0] = 'q4xda5xdn/CLOUDY.png';
link[1] = '7141ttkjf/Heavyrain.png';
link[2] = 'gzp0gatyz/lightrain.png';
link[3] = 'xc3njrxob/Medium_Rain.png';
link[4] = 'x0m770h8b/NO_WEATHER.png';
link[5] = 's38mlwf97/omgrain.png';
link[6] = 'btigj04l7/Special_Weather.png';
link[7] = 'b59m025vf/WEREALLGONNADIErain.png';
link[8] = 'ubmt38md7/Windy.png';
link[9] = 'x0m770h8b/NO_WEATHER.png';
link[10] = 'x0m770h8b/NO_WEATHER.png';
link[11] = '';
link[12] = '';
link[13] = '';
link[14] = '';
link[15] = '';
link[16] = '';
link[17] = '';
link[18] = '';
link[19] = '';
link[20] = '';
link[21] = '';
link[22] = '';
link[23] = '';
link[24] = '';
link[25] = '';
link[26] = '';
link[27] = '';
link[28] = '';
link[29] = '';
link[30] = '';
var currentdate = new Date();
var dM = currentdate.getDate() - 1;
var dW = currentdate.getDay();
//var imagenumber = currentdate.getDay();
document.write('<div id="NOTICEME"><center><img src="' + imlocation + image[dW] + '"><img src="' + imlocation + link[dM] + '"></center><br><div id="mowords">[center][img]' + imlocation + image[dW] + '[/img][img]' + imlocation + link[dM] + '[/img][/center]</div></div>');
//--></script>
You use the function getDay() on the currentDate, therefore it will not change throughout a single day. Have a look at http://www.w3schools.com/jsref/jsref_getday.asp where you notice that its an integer from 0 to 6, and the week starts on sunday.
Therefore today (wednesday august 03 is 3) you should see image[3] and link[3]. Tomorrow you should get an error because you will reference outside of the image array i.e. image[4] will throw an index out of bounds exception.
Well, here goes my first answer here ever!
JavaScript is client-side code, so if the JavaScript code is what is determining the random number (rather than server-side code), you can't guarantee everyone accessing the site sees the same thing.
You could, however, use the date and time as a seed to generate what could appear random:
var btn = document.getElementById('btn');
btn.onclick = function () {
var d = new Date();
// getHours() results in an integer 0-23
var h = d.getUTCHours();
var chooser;
//Pick a multiplier based on the time of day.
if (h < 12) {
chooser = 1.15;
} else {
chooser = 1.87;
}
//Change upperLimit to whatever the upper limit of your array may end up being.
var upperLimit = 10;
//Generate the result
var pseudoRand = parseInt((d.getUTCFullYear() + d.getUTCMonth() + d.getUTCDay()) * chooser % upperLimit);
btn.textContent = pseudoRand;
}
Fiddle: https://jsfiddle.net/tapjzg94/
That code replaces the text of the button with an integer from 0 to upperLimit that should be the same for everyone who clicks on it, avoiding time zone issues with the UTC versions of the Date functions.
You could mix and match the date functions however you want, so long as they are all numbers that don't change on a rapid basis (year/month/date/day vs. minutes/seconds/milliseconds).

iterate through JSON object with pause before next iteration

I am trying to build a fake chat box. I can retrieve the data from the database using jQuery to return a JSON array ok. I then i want each line of text contained in the JSON object to display on the page one line at a time BUT the code must pause for the length of time it would normally take to type the line if text before it displays it. then the code must wait for it to be displayed before it iterated on to the next value in the JSON object.
I hope all that makes sense...
$.getJSON('includes/get-mentor-dialogue.php?e=' + new Date().getTime(), function(data){
var mainDialogue = data.item;
var l = mainDialogue.length;
$.each(mainDialogue, function(index, d){
var delay = Math.round(countWords(d.content) / WPS) * 1000;
setTimeout(function(){$('#chatBox #chatBody').append('<p>'+ d.content +'</p>');},delay);
});
});
This is what i have and it kinda works... countWords() is a function that returns the number of words in the sentence and WPS is a variable that contains the average "Words Per Second" value in it.
The issue is that all the lines of text are displayed out of sequence. i can't get it to wait for the previous line to be displayed before it moves on to the next one...
Really need help with this one guys...
You can use a function to iterate with timeout, without using the $.each, see below
$.getJSON('includes/get-mentor-dialogue.php?e=' + new Date().getTime(), function(data){
var mainDialogue = data.item;
var l = mainDialogue.length;
var actual = -1;
function showNextMessage(){
actual++;
if( actual >= l ) return;
var content = mainDialogue[actual].content;
var delay = Math.round(countWords(content) / WPS) * 1000;
setTimeout(function(){
$('#chatBox #chatBody').append('<p>'+ content +'</p>');
showNextMessage();
},delay);
}
showNextMessage();
});
I think this will work for you.
$.getJSON('includes/get-mentor-dialogue.php?e=' + new Date().getTime(), function(data){
var mainDialogue = data.item;
var l = mainDialogue.length;
var i = 0;
function appendText(content) {
var delay = Math.round(countWords(content) / WPS) * 1000;
if ( i < l - 1 ) {
setTimeout(function(){
$('#chatBox #chatBody').append('<p>'+ content +'</p>');
appendText(mainDialogue[i++].content);
}, delay);
}
};
appendText(mainDialogue[i++].content);
});
I usually create an Iterator class, somewhere along the lines of this:
Iterator = function (iterable) {
var keys = [];
for (var i in iterable)
keys.push(i);
var pointer = 0;
this.next = function () {
return keys[pointer++];
}
this.hasNext = function () {
return i < keys.length;
}
}
That way you don't have to directly iterate across the object, you can just easily keep track of your place in the object as you would in Java.
$.getJSON('includes/get-mentor-dialogue.php?e=' + new Date().getTime(), function(data){
var mainDialogue = data.item;
var l = mainDialogue.length;
var iter = new Iterator(mainDialogue);
(function appendChat () {
var d = iter.next();
var delay = Math.round(countWords(d.content) / WPS) * 1000;
$('#chatBox #chatBody').append('<p>'+ d.content + '</p>');
if (iter.hasNext())
setTimeout(appendChat, delay);
})();
});
I don't have a good way to test this, but you should look into doing something like this:
$.getJSON('includes/get-mentor-dialogue.php?e=' + new Date().getTime(), function(data){
var mainDialogue = data.item;
var l = mainDialogue.length;
var delay = 0;
$.each(mainDialogue, function(index, d){
var myDelay = Math.round(countWords(d.content) / WPS) * 1000;
myDelay+=delay; // how long it takes me to render + the guy before me
delay=myDelay + (Math.random()*2000); // this will give a random pause between each step
setTimeout(function(){$('#chatBox #chatBody').append('<p>'+ d.content +'</p>');},myDelay);
});
});
I added in that little random bit, to help give a more realistic variable timing to the chat sequence.

Change Label Text Periodically Javascript

I try to change a label's text periodically by using the following code:
function sleep(milliSeconds) {
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliSeconds);
}
function showMap() {
var str = document.getElementById("lbPoints").firstChild.nodeValue;
var lbl = document.getElementById("my");
var strs = str.split("-");
var millisecondsToWait = 500;
for (var i = 0; i < strs.length-1; i++) {
lbl.innerHTML = strs[i];
sleep(500);
}
}
My "str" and "strs" are right. Code works, but as waits for 5 seconds and print the final string in strs to screen and nothing else. What can I do to change it periodically?
That's not how you sleep. In no language is it correct to test repeatedly
until a date.
Do this instead :
function showMap() {
var str = document.getElementById("lbPoints").firstChild.nodeValue;
var lbl = document.getElementById("my");
var strs = str.split("-");
var millisecondsToWait = 500;
var i=0;
var interval = setInterval(function(){
if (i==strs.length-2) clearInterval(interval);
lbl.innerHTML = strs[i++];
}, millisecondsToWait);
}
Demonstration
This uses setInterval to call repeatedly a function, and clearInterval at the end of array to stop the function being called.
Just use setInterval, that's what it's for. From the documentation:
Calls a function or executes a code snippet repeatedly, with a fixed
time delay between each call to that function.

Categories

Resources