setTimeout() in javascript

David101

Member
Jul 13, 2003
69
0
66
sooo..i'm pretty new at programming in general and i decided to make a site to learn a bit about css/java/asp which im hosting on my router (lol).

anyways...i'm making a "view code" object, which is a link that expands a box and grabs data from txt files on my server using xmlhttprequest and show it in my formatted code box. this works fine, but i'm trying to make it fancy and have a "Loading..." text with a nice animation for like 500 msecs using setTimeout AND IT'S DRIVING ME NUTS!!! I apparently don't understand all the stuff on the internet explaining this. i've tried dozens of iterations of my code but none seem to work. could someone point out where I'm going wrong? Kinda frustrating :/

thanks,

david


here are the functions:
PHP:
function toggle(txt) {
	var ele = document.getElementById("toggleText");
	var text = document.getElementById("displayText");
	if(ele.style.display == "block") {
    	ele.style.display = "none";
		text.innerHTML = "view";
  	}
	else {
		ele.style.display = "block";
		text.innerHTML = "hide";
		setTimeout(getData(txt), 500);
	}
} 
function getData(txt) {
		var req = null;
		if(window.XMLHttpRequest)
			req = new XMLHttpRequest(); 
		else if (window.ActiveXObject)
			req  = new ActiveXObject(Microsoft.XMLHTTP); 
		req.onreadystatechange = function()
		{ 
			if(req.readyState == 4)
			{
				if(req.status == 200)
				{
					document.getElementById("getCode").innerHTML="<code>" + req.responseText + "</code>";
				}	
			} 
		}
		req.open("GET", txt, true);
		req.send(null);		
}

and the code used to trigger it:
PHP:
<a id="displayText" href="javascript:toggle('data.txt');">view</a>
		<div id="toggleText" style="display: none">			
			<p>
			<div id="getCode"><code><img src="1-1.gif"/> Loading...</code></div>		
			</p>	
		</div>
 

sourceninja

Diamond Member
Mar 8, 2005
8,805
65
91
I'm confused, you want to delay the actual ajax call 500ms so a loading icon can be displayed? Wouldn't it be better to put the loading icon in the function that does the ajax call so it appears before the ajax is running and disappears when the ajax is complete?

Honestly, I don't write pure javascript anymore. I use jquery where this is made a lot simpler. It could be done as easy as.
PHP:
$("#loading").ajaxStart(function(){
   $(this).show();
 });
$("#loading").ajaxStop(function(){
   $(this).hide();
 });

$('#displayText').click(function() {
    $('#getCode').load('data.txt');
});

(this was sudo code and not checked for 100% accuracy)
 

PhatoseAlpha

Platinum Member
Apr 10, 2005
2,131
21
81
Try this.

Code:
var Interval;
var CurrentAnimationStage = 0;
var LoadMessage = document.getElementById("LoadMessage");
var LoadWheel = [".", "..", "...", "...."];
function toggle(txt) {
    var ele = document.getElementById("toggleText");
    var text = document.getElementById("displayText");
    if(ele.style.display == "block") {
        ele.style.display = "none";
        text.innerHTML = "view";
      }
    else {
        ele.style.display = "block";
        text.innerHTML = "hide";
		getData(txt);
		setInterval(Animate(), 100);
    }
}

function Animate(){
	CurrentAnimationStage += 1;
	if (CurrentAnimationStage > 3)
		{
		CurrentAnimationStage = 0;
		}
	LoadWheel.innerHTML = "Loading" + LoadWheel[CurrentAnimationStage];
}

function getData(txt) {
        var req = null;
        if(window.XMLHttpRequest)
            req = new XMLHttpRequest(); 
        else if (window.ActiveXObject)
            req  = new ActiveXObject(Microsoft.XMLHTTP); 
        req.onreadystatechange = function()
        { 
            if(req.readyState == 4)
            {
                if(req.status == 200)
                {
					document.clearInterval(Interval);
                    document.getElementById("getCode").innerHTML="<code>" + req.responseText + "</code>";
                }
				else
				{
					document.clearInterval(Interval);
					document.getElementById("getCode").innerHTML = "There was an error with this request.";
				}
            } 
        }
        req.open("GET", txt, true);
        req.send(null);        
}

with HTML

Code:
<a id="displayText" href="javascript:toggle('data.txt');">view</a>
        <div id="toggleText" style="display: none">            
            <p>
            <div id="getCode"><code><img src="1-1.gif"/><span id='LoadMessage'>Loading...</span></code></div>        
            </p>    
        </div>


Reasoning: If an animation is what you're after, intervals are appropriate - timeouts are for once and done delays, not repeating occurrences. The click starts the animation (the Animate function is called every 100 milliseconds until cleared, which causes the animation). The AJAX request is made immediately, and when it is finished loading, it ends the interval and shows the text.

The variables are for the animation. In my experience, getElementById takes up enough time that if you're going to be using an element often, it should be cached.
 

David101

Member
Jul 13, 2003
69
0
66
hi guys,

first, thanks for the replies. i'll prob stick with javascript for now instead of jquery since i wanna learn what's behind it before i go the easier route. also thanksfor that animation script, i'm using it now .

however, it turns out that i didn't explain myself properly, but i managed to figure it out . what i meant was that the loading time is instant, since the data i'm getting will alwaysbe <10kb and its hosted locally, so i just wanted a "fake" delay with the loading animation.

the way i fixed my code (had a hunch but didn't know the syntax, etc.) was executing my setTimeout like so

setTimeout(function(){getData(txt)},1000);

since i had to pass an argument it always executed the function first since i had to include the (). i found this little piece of gold here if anyone is interested.

thanks again,

david

p.s. there were a few things i had to change in the animation script to get it working
 
sale-70-410-exam    | Exam-200-125-pdf    | we-sale-70-410-exam    | hot-sale-70-410-exam    | Latest-exam-700-603-Dumps    | Dumps-98-363-exams-date    | Certs-200-125-date    | Dumps-300-075-exams-date    | hot-sale-book-C8010-726-book    | Hot-Sale-200-310-Exam    | Exam-Description-200-310-dumps?    | hot-sale-book-200-125-book    | Latest-Updated-300-209-Exam    | Dumps-210-260-exams-date    | Download-200-125-Exam-PDF    | Exam-Description-300-101-dumps    | Certs-300-101-date    | Hot-Sale-300-075-Exam    | Latest-exam-200-125-Dumps    | Exam-Description-200-125-dumps    | Latest-Updated-300-075-Exam    | hot-sale-book-210-260-book    | Dumps-200-901-exams-date    | Certs-200-901-date    | Latest-exam-1Z0-062-Dumps    | Hot-Sale-1Z0-062-Exam    | Certs-CSSLP-date    | 100%-Pass-70-383-Exams    | Latest-JN0-360-real-exam-questions    | 100%-Pass-4A0-100-Real-Exam-Questions    | Dumps-300-135-exams-date    | Passed-200-105-Tech-Exams    | Latest-Updated-200-310-Exam    | Download-300-070-Exam-PDF    | Hot-Sale-JN0-360-Exam    | 100%-Pass-JN0-360-Exams    | 100%-Pass-JN0-360-Real-Exam-Questions    | Dumps-JN0-360-exams-date    | Exam-Description-1Z0-876-dumps    | Latest-exam-1Z0-876-Dumps    | Dumps-HPE0-Y53-exams-date    | 2017-Latest-HPE0-Y53-Exam    | 100%-Pass-HPE0-Y53-Real-Exam-Questions    | Pass-4A0-100-Exam    | Latest-4A0-100-Questions    | Dumps-98-365-exams-date    | 2017-Latest-98-365-Exam    | 100%-Pass-VCS-254-Exams    | 2017-Latest-VCS-273-Exam    | Dumps-200-355-exams-date    | 2017-Latest-300-320-Exam    | Pass-300-101-Exam    | 100%-Pass-300-115-Exams    |
http://www.portvapes.co.uk/    | http://www.portvapes.co.uk/    |