473,700 Members | 2,564 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Newbie needs help with setInterval

Hi Folks,

I'm new to Javascript and just need a little help. I downloaded a
script from Dynamic Drive's Web site and I'm trying to make a simple
modification and could use some help. :)

The script below fetches data from the web server and displays it in
the form as a ticker on the web page. See: http://www.dynamicdrive.com/dynamici...ajaxticker.htm

What I would like to do is to have the Ajax ticker periodically go out
and refetch the XML data say once every five seconds. The way it
operates now it only fetches the data when the page loads. Is there a
simple way to accomplish this? I've tried using
setInterval(thi s.getXMLfile(), 5000) on line 46 with no success, but
it's most likely the way I'm using it. See script script below.

Any help would be greatly appreciated. :)

Thanks,
Shawn
// -------------------------------------------------------------------
// Ajax XML Ticker (txt file source)
// Author: Dynamic Drive (http://www.dynamicdrive.com)
// -------------------------------------------------------------------

////////////No need to edit beyond here//////////////

function createAjaxObj() {
var httprequest=fal se
if (window.XMLHttp Request){ // if Mozilla, Safari etc
httprequest=new XMLHttpRequest( )
if (httprequest.ov errideMimeType)
httprequest.ove rrideMimeType(' text/xml')
}
else if (window.ActiveX Object){ // if IE
try {
httprequest=new ActiveXObject(" Msxml2.XMLHTTP" );
}
catch (e){
try{
httprequest=new ActiveXObject(" Microsoft.XMLHT TP");
}
catch (e){}
}
}
return httprequest
}

// -------------------------------------------------------------------
// Main Ajax Ticker Object function
// ajax_ticker(xml file, divId, divClass, delay, optionalfadeorn ot)
// -------------------------------------------------------------------

function ajax_ticker(xml file, divId, divClass, delay, fadeornot){
this.xmlfile=xm lfile //Variable pointing to the local ticker xml file
(txt)
this.tickerid=d ivId //ID of ticker div to display information
this.delay=dela y //Delay between msg change, in miliseconds.
this.mouseoverB ol=0 //Boolean to indicate whether mouse is currently
over ticker (and pause it if it is)
this.pointer=0
this.opacitystr ing=(typeof fadeornot!="und efined")? "width: 100%;
filter:progid:D XImageTransform .Microsoft.alph a(opacity=100); -moz-
opacity: 1" : ""
if (this.opacityst ring!="") this.delay+=500 //add 1/2 sec to account
for fade effect, if enabled
this.opacityset ting=0.2 //Opacity value when reset. Internal use.
this.messages=[] //Arrays to hold each message of ticker
this.ajaxobj=cr eateAjaxObj()
document.write( '<div id="'+divId+'" class="'+divCla ss+'"><div
style="'+this.o pacitystring+'" >Initializing ticker...</div></div>')
/////////////line added with no success////
setInterval(thi s.getXMLfile(), 5000)
}

// -------------------------------------------------------------------
// getXMLfile()- Use Ajax to fetch xml file (txt)
// -------------------------------------------------------------------

ajax_ticker.pro totype.getXMLfi le=function(){
if (this.ajaxobj){
var instanceOfTicke r=this
var url=this.xmlfil e+"?bustcache=" +new Date().getTime( )
this.ajaxobj.on readystatechang e=function()
{instanceOfTick er.initialize() }
this.ajaxobj.op en('GET', url, true)
this.ajaxobj.se nd(null)
}
}

// -------------------------------------------------------------------
// initialize()- Initialize ticker method.
// -Gets contents of xml file and parse it using JavaScript DOM
methods
// -------------------------------------------------------------------

ajax_ticker.pro totype.initiali ze=function(){
if (this.ajaxobj.r eadyState == 4){ //if request of file completed
if (this.ajaxobj.s tatus==200 ||
window.location .href.indexOf(" http")==-1){ //if request was successful
this.contentdiv =document.getEl ementById(this. tickerid).first Child //
div of inner content that holds the messages
var xmldata=this.aj axobj.responseT ext
this.contentdiv .style.display= "none"
this.contentdiv .innerHTML=xmld ata
if (this.contentdi v.getElementsBy TagName("div"). length==0){ //if no
messages were found
this.contentdiv .innerHTML="<b> Error</bfetching remote ticker file!"
return
}
var instanceOfTicke r=this
document.getEle mentById(this.t ickerid).onmous eover=function( )
{instanceOfTick er.mouseoverBol =1}
document.getEle mentById(this.t ickerid).onmous eout=function()
{instanceOfTick er.mouseoverBol =0}
if (window.attachE vent) //Clean up loose references in IE
window.attachEv ent("onunload", function()
{instanceOfTick er.contentdiv=i nstanceOfTicker .ajaxobj=null})
//Cycle through XML object and store each message inside array
for (var i=0; i<this.contentd iv.getElementsB yTagName("div") .length; i+
+){
if (this.contentdi v.getElementsBy TagName("div")
[i].className=="me ssage")
this.messages[this.messages.l ength]=this.contentdi v.getElementsBy TagName("div")
[i].innerHTML
}
this.contentdiv .innerHTML=""
this.contentdiv .style.display= "block"
this.rotatemsg( )
}
}
}

// -------------------------------------------------------------------
// rotatemsg()- Rotate through ticker messages and displays them
// -------------------------------------------------------------------

ajax_ticker.pro totype.rotatems g=function(){
var instanceOfTicke r=this
if (this.mouseover Bol==1) //if mouse is currently over ticker, do
nothing (pause it)
setTimeout(func tion(){instance OfTicker.rotate msg()}, 100)
else{ //else, construct item, show and rotate it!
this.fadetransi tion("reset") //FADE EFFECT- RESET OPACITY
this.contentdiv .innerHTML=this .messages[this.pointer]
this.fadetimer1 =setInterval(fu nction()
{instanceOfTick er.fadetransiti on('up', 'fadetimer1')}, 100) //FADE
EFFECT- PLAY IT
this.pointer=(t his.pointer<thi s.messages.leng th-1)? this.pointer+1 : 0
setTimeout(func tion(){instance OfTicker.rotate msg()}, this.delay) //
update container periodically
}
}

// -------------------------------------------------------------------
// fadetransition( )- cross browser fade method for IE5.5+ and Mozilla/
Firefox
// -------------------------------------------------------------------

ajax_ticker.pro totype.fadetran sition=function (fadetype, timerid){
var contentdiv=this .contentdiv
if (fadetype=="res et")
this.opacityset ting=0.2
if (contentdiv.fil ters && contentdiv.filt ers[0]){
if (typeof contentdiv.filt ers[0].opacity=="numb er") //IE6+
contentdiv.filt ers[0].opacity=this.o pacitysetting*1 00
else //IE 5.5
contentdiv.styl e.filter="alpha (opacity="+this .opacitysetting *100+")"
}
else if (typeof contentdiv.styl e.MozOpacity!=" undefined" &&
this.opacitystr ing!=""){
contentdiv.styl e.MozOpacity=th is.opacitysetti ng
}
else
this.opacityset ting=1
if (fadetype=="up" )
this.opacityset ting+=0.1
if (fadetype=="up" && this.opacityset ting>=1)
clearInterval(t his[timerid])
}
Sep 21 '08 #1
2 2784
On Sep 21, 4:52*pm, shawnwperk...@g mail.com wrote:
Hi Folks,

I'm new to Javascript and just need a little help. I downloaded a
script from Dynamic Drive's Web site and I'm trying to make a simple
modification and could use some help. :)

The script below fetches data from the web server and displays it in
the form as a ticker on the web page. See:http://www.dynamicdrive.com/dynamici...ajaxticker.htm

What I would like to do is to have the Ajax ticker periodically go out
and refetch the XML data say once every five seconds. The way it
operates now it only fetches the data when the page loads. Is there a
simple way to accomplish this? I've tried using
setInterval(thi s.getXMLfile(), 5000) on line 46 with no success, but
it's most likely the way I'm using it. See script script below.
Well, without spending a lot of time analyzing this code, one simple
thing to fix is changing "this.getXMLfil e()" to "this.getXMLfil e".
The former actually calls the function, and the return value from that
function is what setInterval is going to attempt to call, which is
certainly not what you intended. Removing the parens makes this a
function object, not a function call, which has a much better chance
of working.
Sep 22 '08 #2
On Sep 22, 4:52*am, shawnwperk...@g mail.com wrote:
What I would like to do is to have the Ajax ticker periodically go out
and refetch the XML data say once every five seconds. The way it
operates now it only fetches the data when the page loads. Is there a
simple way to accomplish this? I've tried using
setInterval(thi s.getXMLfile(), 5000) on line 46 with no success, but
it's most likely the way I'm using it. See script script below.

Any help would be greatly appreciated. :)
Maybe what you wanted to do was use the variant of setInterval() which
accepts a Javascript expression in the form of Javascript String i.e.
setInterval("th is.getXMLFile() ", 5000). But then again, it won't work
in your case since `this' when used in such a context always refers to
the global window object. As already suggested, use the second variant
of setInterval() which accepts a Function object as its first
parameter. See < http://developer.mozilla.org/en/DOM/window.setInterval
>
/sasuke
Sep 22 '08 #3

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

Similar topics

28
20328
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()', this.pinginterval); - but is there no way to do this without using the literal ObjectName? If I write 'this.methodName()' I get "Line 1 Char 1: Object doesn't support this property or method." in IE, and nothing happens in Firebird.
10
7786
by: Richard A. DeVenezia | last post by:
At line this.timerId = setInterval (function(){this.step()}, 100) I get error dialog Error:Object doesn't support this property or method. If I change it to this.timerId = setInterval (function(){this==window}, 100) I see true, the sad fact that 'this' is window and not an anim. What are some proper ways ? I would like to avoid
17
2123
by: George Hester | last post by:
Hoe can I use setInterval where its argument is a function which also has an argument? For example I have a function change(Msg) where Msg is dynamically generated and returns nothing at this point (other than true I guess). I would like to have setInterval(change(Msg)); but that doesn't work. Any suggestions? Thanks. -- George Hester __________________________________
6
15224
by: marktm | last post by:
Hi- I am trying to use setInterval to call a method within an object and have not had any luck. I get "Object doesn't support this property or method" when I execute the following code. What I am doing wrong? Your help will be much appreciated. Thanks
4
3251
by: barry | last post by:
If The script below is exeuted from the onload="startit()" in the body tag everything works fine but when I remove the onload and try to execute by using the attributes.add from within the Page_Load the window.setInterval will not execute - there is no message but the timer never takes off. I put an alert in the startit() and it did appear so the attributes.add is working ok. Would appreciate any help thanks Private Sub...
1
2401
by: Terry | last post by:
Hi folks. I tried to use setInterval like this but it did not work setInterval ( removeitem (theitem) { theitem.style.display= "none"; }, 1000 ); the function without the setInterval is
1
1433
by: Jeff | last post by:
I've been trying to pass in an object in a setInterval but it complains about missing ] after elenment list. setInterval("someFunction("+some_object+")",1000); What's the correct syntax to do this? Jeff
7
2466
by: kaiser0427 | last post by:
Ok, I have cleaned up the code and fixed some errors in it. The problem I am having is with the timer. If you uncomment the alert it pauses after every record. when I replace it with setInterval it runs through the code but doesn't pause. First time using setInterval and any help will be appreciated. // in the head var c=0; var t; function wait() { document.getElementById('targetDiv').value=c; c+=1; }
0
8731
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
8649
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
9219
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
8931
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
7819
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...
0
4660
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3097
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2032
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.