Javascript array:
var urls = ['https://www.google.com', 'https://www.msn.com', 'https://stackoverflow.com'];
I am having the array of URLs. I want to open each URL every 15 seconds in a new tab or window.
function g(){
setTimeout(o, 1);
}
function o(){
window.open('page.php');
}
The above code is not working.
I think you are finding setInterval.
var urls = ['https://www.google.com', 'https://www.msn.com', 'https://stackoverflow.com'];
var index = 0;
var interval = setInterval(o, 15000);
function o() {
if (typeof urls[index] !== typeof undefined) {
window.open(urls[index]);
index++;
} else {
clearInterval(interval);
}
}
Fiddle
Related
I'm trying to make a web page that has its wallpaper change every time you refresh. I'd like it to display the next image in the array every time the page is refreshed. So every refresh works its way through the list until the end, and then starts over.
Right now I'm using an array and accessing it with a random index, but I need to access it using one that increases by 1 each time, and once I reach the array length I need it to start over again... Right now I'm using this (which took me forever to figure out):
$(function background() {
var images = [
"wallpaper1.jpg",
"wallpaper2.jpg",
"wallpaper3.jpg",
"wallpaper4.jpg"
];
$("#hero").css({
"background-image":
"url(images/wallpapers/" +
images[Math.floor(Math.random() * images.length)]
+ ")"
});
});
I have found out about incrementing numbers in an array using this:
var arr = [1,2,3,4];
arr = arr.map(function(val){return ++val;});
console.log(arr);
But I can't seem to get the number solution to work with strings. I'm ultra new at all this and I am losing my mind :/
You need to save a counter to localStorage that you can retrieve on each page load, increment,, make the check, and then save again.
$(function () {
const images = [
'wallpaper1',
'wallpaper2',
'wallpaper3',
'wallpaper4'
];
// We must check to see if localStorate exists before
// we do anything
function hasLocalStorage() {
try {
localStorage.setItem('count', 0);
if (localStorage.getItem('count') === '0') {
return true;
}
} catch(e) {
return false;
}
return false;
}
// Fetch the count from localStorage. Because it's
// saved as a string we need to coerce it to a number
let count = Number(localStorage.getItem('count'));
$("#hero").css({
'background-image': `url(${images[count]})`
});
// Increase the count
count++;
// If the count is the length of the array (minus one
// because the array is indexed-based) set the
// localStorate count to zero, otherwise save the count
if (count === images.length - 1) {
localStorage.setItem('count', 0);
} else {
localStorage.setItem('count', count);
}
});
You can add a helper function to do this:
var getNextImage = (() => {
var i = 0;
return () => {
if (i >= images.length)
{
i = 0;
}
return images[i++];
};
})();
and then replace the images[Math.floor(Math.random() * images.length)] call with getNextImage()
Like so:
$(function background() {
var images = [
"wallpaper1.jpg",
"wallpaper2.jpg",
"wallpaper3.jpg",
"wallpaper4.jpg"
];
var getNextImage = (() => {
var i = 0;
return () => {
if (i >= images.length)
{
i = 0;
}
return images[i++];
};
})();
$("#hero").css({
"background-image":
"url(images/wallpapers/" + getNextImage() + ")"
});
});
<!DOCTYPE html>
<html>
<body>
<script>
// Checking if the Local Storage feature is available.
if (typeof(Storage) !== "undefined") {
// If it is available, check if there is a value stored by the name 'val'.
if(localStorage.getItem("val") != null) {
// If yes increase it by 1.
localStorage.setItem("val", parseInt(localStorage.getItem("val")) + 1);
}
else {
// If no then create one and set it to 1.
localStorage.setItem("val", 1);
}
// Printing the value on the console and the page to check if it is working (You can remove this later.)
console.log(localStorage.getItem("val"));
document.write(localStorage.getItem("val"));
}
// If it is not available notify the user.
else {
console.log("Sorry, your browser does not support Web Storage...");
document.write("Sorry, your browser does not support Web Storage...");
}
var num = parseInt(localStorage.getItem("val"));
</script>
</body>
</html>
Local Storage is a feature is in HTML. It can be used to store data in the tab and will be there as long as the tab isn't closed. So, now whenever you reload your page you will get the next number starting from one.
Possible, but the persistence is only becuase of the localStorage
Hey! Check this out.
This basically selects an image from the array and then changes the background continuously according to the current image. If the last image (when the user last visited the page) was wallpaper4.jpg, the next would be automatically the wallpaper1.jpg.
Assuming that the target browser has localStorage enabled, this would be the JavaScript code
var images = [
"wallpaper1.jpg",
"wallpaper2.jpg",
"wallpaper3.jpg",
"wallpaper4.jpg"
];
getBgImage = () => {
var lastImage = localStorage.getItem("wallpaperIdx");
if (lastImage && images.indexOf(lastImage) < (images.length - 1) && images.indexOf(lastImage) >= 0) {
localStorage.setItem("wallpaperIdx", images[(images.indexOf(lastImage) + 1)]);
return images[(images.indexOf(lastImage) + 1)];
} else if (images.indexOf(lastImage) === (images.length - 1)) {
localStorage.setItem("wallpaperIdx", images[0]);
return images[0];
} else {
localStorage.setItem("wallpaperIdx", images[0]);
return images[0];
}
}
$(function () {
setInterval(() => {
var image = getBgImage();
$('#hero').css({
"background-image": `url("images/wallpapers/${image}")`,
"transition": "1s"
});
}, 1000)
clearInterval();
});
$(() => {
$(window).on("load", () => {
document.getElementById("hero").style.backgroundImage = `url("images/wallpapers/${image}")`;
})
})
I was wondering why my program crashes after its made its first match....any ideas would be greatly appreciated. Below is the code snippet. Thanks for the input!
var clicks = 0; //counts how may picks have been made in each turn
var firstchoice; //stores index of first card selected
var secondchoice; //stores index of second card selected
var match = 0; //counts matches made
var backcard = "deck.jpg"; //shows back of card when turned over
var faces = []; //array to store card images
faces[0] = 'pic1.jpg';
faces[1] = 'pic2.jpg';
faces[2] = 'pic3.jpg';
faces[3] = 'pic3.jpg';
faces[4] = 'pic2.jpg';
faces[5] = 'pic1.jpg';
function choose(card) {
if (clicks === 2) {
return;
}
if (clicks === 0) {
firstchoice = card;
document.images[card].src = faces[card];
clicks = 1;
} else {
clicks = 2;
secondchoice = card;
document.images[card].src = faces[card];
timer = setInterval("check()", 1000);
}
}
/* Check to see if a match is made */
function check() {
clearInterval(timer); //stop timer
if (faces[secondchoice] === faces[firstchoice]) {
match++;
document.getElementById("matches").innerHTML = match;
} else {
document.images[firstchoice].src = backcard;
document.images[secondchoice].src = backcard;
clicks = 0;
return;
}
}
The first parameter of setInterval needs to be a function not a string pretending to be a function. So you would want this:
timer = setInterval(function() { check(); }, 1000);
Of course, you can simplify:
timer = setInterval(check, 1000);
Not sure why you're using setInterval() here. You could more easily just do:
timer = setTimeout(check, 1000);
The advantage is there is no interval to clear in the check() function.
The other issue is that you are not resetting your 'clicks' counter to 0 when there is a match.
You want this:
function check() {
clearInterval(timer); //stop timer
if (faces[secondchoice] === faces[firstchoice]) {
match++;
document.getElementById("matches").innerHTML = match;
} else {
document.images[firstchoice].src = backcard;
document.images[secondchoice].src = backcard;
}
clicks = 0;
}
I think you have to declare you timer function globally. Its only defined in the scope of the first function, so in the second when you try to clear it nothing happens:
var timer = ''; //Declare timer up here first!
function choose(card) { ... }
function check() { ... }
I am using google maps and i am trying to put a pause in execution to prevent QUERY_LIMIT usage issue. My function that plots the addresses looks like this.
The code works, however i want to try setTimeout or setInterval to see if its going to look better on UI.
How do i call it, what should be the first argument?
Thanx alot.
vLocations = [];
for (var i = 0; i < vAddresses.length; i++) {
//pause to prevent OVER_QUERY_LIMIT issue
//geocode "free" usage limit is 5 requests per second
//setTimeout(PlotAddressesAsUnAssigned, 1000);
//sleep(500);
//this will resolve the address and store it in vLocations
AddWaypointAndUnassigned(vAddresses[i]);
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
}
Doing a pause (asynchronous execution) inside a loop (synchronous) will usually result in a lot of trouble.
You can use recursive calls that are done only when a timeout ends.
var vLocations = [];
// Manages the timeout and recursive calls
function AddWaypointAndUnassignedWithPause(index){
setTimeout(function(){
// When the timeout expires, we process the data, and start the next timeout
AddWaypointAndUnassigned(vAddresses[index]);
// Some other code you want to execute
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
if(index < vAddresses.length-1)
AddWaypointAndUnassignedWithPause(++index);
}, 1000);
}
// Start the loop
AddWaypointAndUnassignedWithPause(0);
JSFiddle example.
Try this, hope this will help
vLocations = [];
for (var i = 0; i < vAddresses.length; i++) {
//pause to prevent OVER_QUERY_LIMIT issue
setTimeout(function(){
//this will resolve the address and store it in vLocations
AddWaypointAndUnassigned(vAddresses[i]);
}, 500);
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
}
What about a waiting line, thats fired when an item is added and stopped when there are no items left.
With setTimeout:
var INTERVAL = 1000 / 5;
var to = null;
var vLocations = [];
function addAddress(vAddress) {
vLocations.push(vAddress);
startTimeout();
}
function startTimeout() {
if( to === null ) {
to = setTimout(processLocation, INTERVAL);
}
}
function processLocation() {
if( vLocations.length ) {
var vAddress = vLocations.shift();
AddWaypointAndUnassigned(vAddress);
to = setTimout(processLocation, INTERVAL);
} else {
to = null;
}
}
With setInterval:
var INTERVAL = 1000 / 5;
var to = null;
var vLocations = [];
function addAddress(vAddress) {
vLocations.push(vAddress);
startInterval();
}
function startInterval() {
if( to === null ) {
to = setInterval(processLocation, INTERVAL);
}
}
function processLocation(cb) {
if( vLocations.length ) {
var vAddress = vLocations.shift();
AddWaypointAndUnassigned(vAddress);
} else
clearInterval(to);
to = null;
}
}
Here I have a simple countdown function that redirects the user after 5 seconds.
<script type="text/javascript">
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown();
}, 1000);
}
else
{
// Redirect the user
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof target === "undefined")
{
window.location.href = target;
}
}
};
var target = "/account/";
countdown(target);
</script>
The problem is, when 5 seconds elapse and it's time for the window.location.href to do the redirection, the "target" variable is undefined, I'm not sure why this happens.
I have researched and tried various solutions, even setting the "target" the way "timer" and "counter" are set, but none worked. My goal is to set a different "target" at each function instance.
UPDATE: Setting countdown(); to countdown(target); fixed the "undefined" issue, but the window.location.href object still doesn't redirect to the target variable value, What can be done to fix this?
You need to pass target to countdown in setTimeout
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown(target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof target === "undefined")
{
window.location.href = target;
}
}
};
Got it, for some reason, the if (!typeof target === "undefined") still returned true even though target was indeed defined, which caused window.location.href to not fire up and redirect to the target value.
UPDATE: I was doing it the wrong way, it was a grouping issue, but using if (typeof target !== "undefined") makes it work as expected.
I'm sharing the fixed code in case it helps someone else:
<script type="text/javascript">
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(
function()
{ countdown(target); }, 1000
);
}
else
{
// Redirect the user
if (typeof target !== "undefined")
{
window.location.href = target;
}
}
};
var target = "/MixaPay/";
countdown(target);
</script>
Thanks everyone who have contributed.
Here is your problem, when you call the countdown function again, you should send the "target" object.
setTimeout(function () {
countdown(); // should be: countdown(target);
}, 1000);
try this, its working, you forgot to pass the argument in your function.
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(timer,target){
counter.innerHTML = timer--;
if (timer > 0)
{
setTimeout(function () {
countdown(timer,target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof str === "undefined")
{
window.location.href = target;
}
}
};
var target = "/account/";
countdown(timer,target);
try using full url instead of using absolute url to redirect like instead of /account/ use localhost/account/
UPDATE This must work I have tested it
<span id="countdown"></span>
<script>
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown(target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
window.location.href = target;
}
};
var target = "/account/";
countdown(target);
</script>
I have a banner rotator that refreshes every 60 seconds however I would also like each banner to be displayed for 20 seconds as there are 3 of them. I know where to put the setInterval code as indicated by my comment but I can't seem to get it to work. Any help or suggestions are very much appreciated.
var banners1 = {
0:
{
'href': 'http://www.example.com/banner1.html',
'src': 'http://www.example.com/banner1.gif'
},
1:
{
'href': 'http://www.example.com/banner2.html',
'src': 'http://www.example.com/banner2.gif'
},
2:
{
'href': 'http://www.example.com/banner3.html',
'src': 'http://www.example.com/banner3.gif'
}
}
window.addEvent('domready', function() {
function banner1()
{
var banner = $('banner1');
var banner1Link = $('banner1').getElement('a');
var banner1Image = $('banner1').getElement('img');
for (var keys in banners1) {
var object = banners1[keys];
for (var property in object) {
if (property == 'href') {
var href = object[property];
}
if (property == 'src') {
var src = object[property];
}
}
banner1Link.setProperty('href', href);
banner1Image.setProperty('src', src);
console.log(href);
console.log(src);
/** wait 20 seconds **/
}
}
var periodical = banner1.periodical(60000);
});
Try this instead:
function banner1()
{
var banner = $('banner1');
var banner1Link = $('banner1').getElement('a');
var banner1Image = $('banner1').getElement('img');
var delay = 0;
for (var keys in banners1) {
var func = (function(key) { return function() {
var object = banners1[key];
for (var property in object) {
if (property == 'href') {
var href = object[property];
}
if (property == 'src') {
var src = object[property];
}
}
banner1Link.setProperty('href', href);
banner1Image.setProperty('src', src);
console.log(href);
console.log(src);
}; })(keys);
setTimeout(func, delay);
delay += 20000;
}
}
JavaScript does not have a sleep-style function, because the document will not respond while JavaScript is running. This means the user would not be able to interact with the page while the script is sleeping.
This approach schedules all three updates in one shot. They will execute at 0 seconds (immediately), 20 seconds, and 40 seconds from the time the script runs.
you could use the javascript timeout
setTimeout('', 20000);
This would be added right after the 20 sec comment. The first variable is any code/function you want called. and the second is the amount of time required before it is called in milliseconds (20 secs).
EDITED ANSWER
<script type="text/javascript">
var imgs1 = new Array("http://www.omniadiamond.com/images/jwplayer/enel_culture.png","http://www.omniadiamond.com/images/jwplayer/evas_srm.png","http://www.omniadiamond.com/images/jwplayer/jackolantern.png");
var lnks1 = new Array("http://test.com","http://test.com","http://test.com");
var alt1 = new Array("test","test","test");
var currentAd1 = 0;
var imgCt1 = 3;
function cycle1() {
if (currentAd1 == imgCt1) {
currentAd1 = 0;
}
var banner1 = document.getElementById('adBanner1');
var link1 = document.getElementById('adLink1');
banner1.src=imgs1[currentAd1]
banner1.alt=alt1[currentAd1]
document.getElementById('adLink1').href=lnks1[currentAd1]
currentAd1++;
}
window.setInterval("cycle1()",20000);
</script>
<a href="http://test.com" id="adLink1" target="_top">
<img src="http://www.omniadiamond.com/images/jwplayer/enel_culture.png" id="adBanner1" border="0"></a>
This does cycle through all three in 60 secs at a 20 sec interval. and can be viewed at http://jsfiddle.net/jawilliams346614/wAKGp/ (it is set to a 1 sec interval)