473,732 Members | 2,175 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why won't this array loop?

Amy
Hello, I have an array with 60 items in it, one for every second, But
when it gets to the end of the 60 items it stops. How do I get it to
start over when it gets to the end of the array? Please let me know,
thank you very much.

arr = new Array(
["Text"],["http://www.website.com "],//to 60 items.
["Text"],["http://www.website.com "]
);
function change()
{
document.getEle mentById("url") .href = arr[new
Date().getSecon ds()-1][0];
document.getEle mentById("url") .innerHTML = arr[new
Date().getSecon ds()-2][0];
setTimeout('cha nge()',1000);
}

Oct 29 '06 #1
6 1398
Amy said the following on 10/29/2006 3:40 AM:
Hello, I have an array with 60 items in it, one for every second, But
when it gets to the end of the 60 items it stops.
It *should* stop when the seconds of the Date object is 0.
How do I get it to start over when it gets to the end of the array?
Please let me know, thank you very much.

arr = new Array(
["Text"],["http://www.website.com "],//to 60 items.
["Text"],["http://www.website.com "]
);
function change()
{
document.getEle mentById("url") .href = arr[new
Date().getSecon ds()-1][0];
When new Date().getSecon ds() hits 0 (at the beginning of a new minute),
then it subtracts one from that and gets -1, there is no -1 entry in
your array so the browser throws an error and halts script execution.

The simplest way to "fix it" is to redefine the way your array is
defined. You can look up Array Literal definitions to see how to shorten
the array definition but if you define it something like this:

var arr = new Array()
arr[0] = new Array('Text for 0','URL for 0');
arr[1] = new Array('Text for 1','URL for 1');
....
arr[58] = new Array('Text for 58','URL for 58');
arr[59] = new Array('Text for 59','URL for 59');

And then change your function:

function change()
{
refToLink = document.getEle mentById("url") ;
currentSeconds = new Date().getSecon ds();
refToLink.href = arr[currentSeconds][0];
refToLink.inner HTML = arr[currentSeconds][1];
}

And then instead of using setTimeout, use setInterval:

window.setInter val('change()', 1000);

Make sure the setInterval statement is *outside* the function.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Oct 29 '06 #2
VK

Amy wrote:
Hello, I have an array with 60 items in it, one for every second, But
when it gets to the end of the 60 items it stops. How do I get it to
start over when it gets to the end of the array? Please let me know,
thank you very much.

arr = new Array(
["Text"],["http://www.website.com "],//to 60 items.
["Text"],["http://www.website.com "]
);
For this purpose a "two-dimensional" array is more benefitial:

<html>
<head>
<title>Dynami c Link</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">

var arr = [
['Text 1', '#URL1'],
['Text 2', '#URL2'],
['Text 3', '#URL3']
];

var dynLink = null;

function init() {
dynLink = document.getEle mentById('url') ;
window.setTimeo ut('changeURL(0 )',1000);
}

function changeURL(i) {
if (i >= arr.length) {
i = 0;
}
dynLink.innerHT ML = arr[i][0];
dynLink.href = arr[i][1];
window.setTimeo ut('changeURL(' +(++i)+')',1000 );
}

window.onload = init;
</script>
</head>

<body>
<p><a id="url" href="">URL</a></p>
</body>
</html>

Oct 29 '06 #3
Amy
Thank you very, very much for your help. I guess it doesn't have to
happen right on the particular second. But if anyone comes up with a
easy way to make my other one loop please let me know. Thats the only
thing wrong with it.
VK wrote:
Amy wrote:
Hello, I have an array with 60 items in it, one for every second, But
when it gets to the end of the 60 items it stops. How do I get it to
start over when it gets to the end of the array? Please let me know,
thank you very much.

arr = new Array(
["Text"],["http://www.website.com "],//to 60 items.
["Text"],["http://www.website.com "]
);

For this purpose a "two-dimensional" array is more benefitial:

<html>
<head>
<title>Dynami c Link</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">

var arr = [
['Text 1', '#URL1'],
['Text 2', '#URL2'],
['Text 3', '#URL3']
];

var dynLink = null;

function init() {
dynLink = document.getEle mentById('url') ;
window.setTimeo ut('changeURL(0 )',1000);
}

function changeURL(i) {
if (i >= arr.length) {
i = 0;
}
dynLink.innerHT ML = arr[i][0];
dynLink.href = arr[i][1];
window.setTimeo ut('changeURL(' +(++i)+')',1000 );
}

window.onload = init;
</script>
</head>

<body>
<p><a id="url" href="">URL</a></p>
</body>
</html>
Oct 29 '06 #4
Lee
Amy said:
>
Hello, I have an array with 60 items in it, one for every second, But
when it gets to the end of the 60 items it stops. How do I get it to
start over when it gets to the end of the array? Please let me know,
thank you very much.

arr = new Array(
["Text"],["http://www.website.com "],//to 60 items.
["Text"],["http://www.website.com "]
);
function change()
{
document.getEl ementById("url" ).href = arr[new
Date().getSeco nds()-1][0];
document.getEl ementById("url" ).innerHTML = arr[new
Date().getSeco nds()-2][0];
setTimeout('ch ange()',1000);
}
It looks to me as if it won't get through all 60 before it
stops due to a run-time error when your indices go outside
the bounds of your assigned values.

Take a moment to figure out what you want your indices to be
in order to display the pair of (text,URL) values for second
number 0, then for second number 1, etc. You'll see that the
pairs of values that you need are (0,1), (2,3), (4,5), ...
Now check to see what values your code is generating for those
same seconds. They're not the same. Also check the values
that you need vs the values that you're generating for second
58 and second 59.

You also take a chance by calling getSeconds() twice. It's
very possible for the value to change between calls, resulting
in a mismatch between text and URL values. You won't see that
very often, but on a very popular website it could happen just
often enough to get a few complaints.

And there's no reason to make each element of the array "arr"
a array containing one element.
--

Oct 29 '06 #5
In message <ei********@drn .newsguy.com>, Sun, 29 Oct 2006 07:47:26, Lee
<RE************ **@cox.netwrite s
>Amy said:
>>function change()
{
document.getE lementById("url ").href = arr[new
Date().getSec onds()-1][0];
document.getE lementById("url ").innerHTM L = arr[new
Date().getSec onds()-2][0];
setTimeout('c hange()',1000);
}
>You also take a chance by calling getSeconds() twice. It's
very possible for the value to change between calls, resulting
in a mismatch between text and URL values. You won't see that
very often, but on a very popular website it could happen just
often enough to get a few complaints.
To clarify : there's no error resulting from calling getSeconds() more
than once on a given Date Object, though it would be more efficient to
store the result in a variable. The source of error is calling new
Date() more than once in an action (when not measuring the passage of
time). The above should start function change() { var D = new Date()
and use D thereafter.

Note that calling setTimeout( , 1000) will in some systems give an
average delay exceeding 1000 ms of the local clock. If every second is
needed, recalculate the delay each time, as in my js-date2.htm#RC and
js-date0.htm#TaI.

It's a good idea to read the newsgroup and its FAQ. See below.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 IE 6
<URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Oct 30 '06 #6
Lee
Dr J R Stockton said:
>
In message <ei********@drn .newsguy.com>, Sun, 29 Oct 2006 07:47:26, Lee
<RE*********** ***@cox.netwrit es
>>Amy said:
>>>function change()
{
document.get ElementById("ur l").href = arr[new
Date().getSe conds()-1][0];
document.get ElementById("ur l").innerHTM L = arr[new
Date().getSe conds()-2][0];
setTimeout(' change()',1000) ;
}
>>You also take a chance by calling getSeconds() twice. It's
very possible for the value to change between calls, resulting
in a mismatch between text and URL values. You won't see that
very often, but on a very popular website it could happen just
often enough to get a few complaints.

To clarify : there's no error resulting from calling getSeconds() more
than once on a given Date Object, though it would be more efficient to
store the result in a variable.
You're right, of course, I started to go on about the inefficiency
of calling the method twice, and then let my mind wander.
--

Oct 30 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
39468
by: deko | last post by:
I need to create a basic one-dimensional array of strings, but I don't know how many strings I'm going to have until the code is finished looping. pseudo code: Dim astrMyArray() Do While Not rst.EOF i = i + 1 If rst!Something = Then astrMyArray(i) = rst!Something
11
24123
by: Walter Dnes (delete the 'z' to get my real address | last post by:
I've noticed a few threads (full of sound and fury, signifying nothing) here recently about allocation of large memory blocks. I'm about to start on a personal pet project where I'll be using memchr(), memcmp(), memmove() a lot. Is there an ANSI C maximium size for character arrays which are guaranteed to succeed, assuming the machine has sufficient memory? And will the memxxx() functions work with that size? I'm looking at hopefully...
8
5409
by: drose0927 | last post by:
Please help! I can't get my program to exit if the user hits the Escape button: When I tried exit(EXIT_SUCCESS), it wouldn't compile and gave me this error: Parse Error, expecting `'}'' 'else if (choice == 27) exit(0) } }' Here is my program (Simple loop to display currency equivalencies based
8
21858
by: Niron kag | last post by:
Hi, I have a loop an in the loop I populate an array of dataRow. My problem is the array keeps its values from previous loop, and its Length gets bigger every loop. My code is: DataRow foundRowsAct; sSQL ="SQL STATEMENT"; foundRowsAct = dtACTIVITIES.Select(sSQL); I tried to write in the loop: foundRowsAct=null;
5
2202
by: =?Utf-8?B?Sm9uYXRoYW4gU21pdGg=?= | last post by:
I have written a service, but it won't stop, Eventvwr reports the following: "Failed to stop service" The code is as follows: ============================================ Protected Overrides Sub OnStart(ByVal args() As String) ' Add code here to start your service. This method should set things ' in motion so your service can do its work.
5
1455
by: jpaterso | last post by:
Here's the code. When I run it, the array prints fine in the while loop but I get the last person in every array element in the for loop. Thanks in advance. File: Jerry,12 Lon,11
2
2110
dlite922
by: dlite922 | last post by:
difficult to explain, easier to show: Here's what my data looks like on the PHP side: Array ( => Array ( => 20003001 => ABC RESTAURANT
3
4486
by: numlock00 | last post by:
I have a nested 'while' loop that won't repeat, no matter how many times the outer loop repeats. The outer loop reads through an array of elements; the inner loop Ithe 'while' loop) is supposed to apply each of these elements while reading an input file. The outer loop is working fine. It will run through every element of the array. The inner loop, however, only runs once. Even though the outer loop finishes inormally, the inner loop does not...
6
2236
by: lukasso | last post by:
Hi, this is my code that should produce something like a timetable for a few days with each day divided into 30 minute pieces. It makes query from MySQL and then creates a 2d $array which then is to be echoed like a table into html. Almost everything goes well except for one entry going for an hour longer and one disappearing if shorter than 1hour (e.g. 30mins) <?php for($i=0; $i<$numRows; $i++) { $result =...
0
8944
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8773
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9445
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9306
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9180
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6733
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4548
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.