473,420 Members | 1,547 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,420 software developers and data experts.

Pause the code execution

nathj
938 Expert 512MB
Hi,

I have a strange problem, my code is running too quickly. Allow me to explain (if I can).

I am using the XMLHTTP object in order to query the database as a user completes the membership application form, basically I want to ensure that each username is unique.

I have the code to check this and the XMLHTTP object is working fine. However, before the code finishes executing the next part of the function is run. this means that the array I have for storing if items are valid or not is being populated incorrectly.

I only check the database if the first stage of validation returns true. At present I have a bit of a fudge in place in that I have added an alert box, as you can see in the code below, this seems to pause the code, which then results in the correct behaviour. Without this I get told that the username I entered is in the database but the system allows me to continue because the validation flag says true because the user name followed the regular expression in place.

Here is the code
Expand|Select|Wrap|Line Numbers
  1. function writeResponse() 
  2.     if (goXMLHTTP.readyState==4 || goXMLHTTP.readyState=="complete")
  3.     { 
  4.        // I did hav a line here testing status=200 but it didn't make any difference document.getElementById(gcItemID).innerHTML=goXMLHTTP.responseText;  
  5.         // set glIsValid based on the return from the database
  6.         glIsValid = goXMLHTTP.responseText.search(/warninglabel/i)>0? false:true; 
  7.     } 
  8.  
  9. function GetXmlHttpObject()
  10.     if (window.XMLHttpRequest)
  11.     {
  12.         goXMLHTTP=new XMLHttpRequest()
  13.     }
  14.     else if (window.ActiveXObject)
  15.     {
  16.         goXMLHTTP=new ActiveXObject("Microsoft.XMLHTTP")
  17.     }     
  18.     if (goXMLHTTP==null)
  19.     {
  20.         alert ("Browser does not support HTTP Request")
  21.          return    
  22.     } 
  23.  
  24.  
  25. function validateItem(pcID,pcItem,pcDisplay,pnType,plPopulateExtra,pnNumberOfItems,plCheckDatabase,pnListItem)    
  26. {    
  27.     var lcRegExp, llUseRegExp
  28.     var lnItemsToValidate = 0 
  29.     glIsValid = false 
  30.     llUseRegExp = false
  31.     switch (pnType)
  32.     {
  33.         case 1:    // UK postcode
  34.             pcItem = pcItem.toUpperCase()     
  35.             lcRegExp = '^[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA$' 
  36.             break;
  37.         case 2: // email address
  38.             lcRegExp = '^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*$'
  39.             break;
  40.         case 3: // number of set length - basic telephone number check
  41.             lcRegExp = '^[0-9 ]{6,13}$'                                            
  42.             break;
  43.         case 4: // password validation - alpha numeric characters 6-18 characters long
  44.             lcRegExp = '^[A-Za-z0-9]{6,18}$' 
  45.             break;    
  46.         case 5: // username validation - alpha numeric characters 6-18 characters long
  47.             lcRegExp = '^[A-Za-z0-9]{6,18}$' 
  48.             break;
  49.         default: // all other validation items
  50.             lcRegExp = '^[A-Za-z0-9 ]{2,30}$'
  51.             break;                         
  52.     }
  53.  
  54.     glIsValid = pcItem.match(lcRegExp)?true:false;
  55.  
  56.     // set the display now
  57.     if (plCheckDatabase) // check the database
  58.     {                         
  59.         if(glIsValid) // only check the database if the item to check is valid from the first stage
  60.         {
  61.             GetXmlHttpObject() // sets the global variable goXMLHTTP
  62.             gcItemID = pcID
  63.             gcUrl = "../lib/datacheck.php?check=" + pnType +"&tocheck='" + pcItem + "'"
  64.             goXMLHTTP.onreadystatechange=writeResponse 
  65.             goXMLHTTP.open("GET",gcUrl,true)
  66.             goXMLHTTP.send(null)
  67.             // update gaValidationList accordingly    
  68.             alert("Checking the database for availability" + '\n' + "Click 'OK' to continue")  // this is used to simply prevent the code from running ahead of itself and explain the process to the user
  69.             // it would be good if a better way could be established - THIS IS THE FUDGE
  70.             setValidationList(pnListItem)
  71.         }
  72.     }
  73.     else // set the display
  74.     {
  75.         document.getElementById(pcID).innerHTML = glIsValid? pcDisplay:"<span class='warninglabel'>" + pcDisplay + "</span>";
  76.         // update gaValidationList accordingly    
  77.         setValidationList(pnListItem)
  78.     }    
  79.  
  80.  
  81.     // structure to ensure that the form is only valid when it is valid
  82.     for (lnItem in gaValidationList)
  83.       {      
  84.         if (gaValidationList[lnItem] == false)
  85.         {
  86.             lnItemsToValidate++
  87.         }
  88.     }     
  89.  
  90.     if (lnItemsToValidate == 0)// everything is valid - let the user continue by setting the disabled property of an item    
  91.     {
  92.         hideOrShowInput("complete",false)    
  93.     }
  94.     else // something is invalid, the user will be able to tell, they need to complete this before moving on 
  95.     {
  96.         hideOrShowInput("complete",true)    
  97.     }
  98.  
  99.     if (plPopulateExtra)
  100.     {
  101.          populateExtra(lcSource, lcDestination, true, true)
  102.     } 
  103. }    
  104.  
  105. function setValidationList(pnListItem)
  106. {
  107.     // gaValidationList is a global array - for the life of the page using it at least    
  108.     gaValidationList[pnListItem] = glIsValid 
  109. }
  110.  
That's all the functions involved at this stage. The PHP file referenced there simply runs some data checks and writes the relevant response back to the screen, so if the item exists the label written to the screen will contain the string "warninglabel"

Is there a better way of pausing the code? I tried setTimeout but that didn't have the desired results.

Any suggestions at all will be welcome. Generally I am quite pleased with this form and the way it validates as the user types - the validateItem() function is called from the onchange event of the input boxes.

Many thanks
Nathan
Jul 4 '07 #1
11 3478
pbmods
5,821 Expert 4TB
Heya, Nathan.

Try calling setValidationList() directly inside of writeResponse().

See this thread for more info.
Jul 4 '07 #2
nathj
938 Expert 512MB
Heya, Nathan.

Try calling setValidationList() directly inside of writeResponse().

See this thread for more info.
I have read the other thread, and felt a bit of a fool for forgetting what Asynchronous meant.

The trouble I have with calling setValidationList() directly is that I can't pass parameters into the function from onreadystatechange.

If I code cause the cde to pause for a bit, without the alert that would be perfect (if a bit of a fudge). Is there are any effective way of doing this?

Alternatively is there a way of passing paramters into the function that is called from onreadystatechange? If there is then perhaps I can move my call to setValidationList() into writeResponse(). That way the code that sets the glIsValid variable will have executed by the time the setValidationList() function is called.

Thanks for the help so far, I have already learnt a lot more about this sort of development.
nathj
Jul 5 '07 #3
pbmods
5,821 Expert 4TB
Heya, Nathan.

The trouble I have with calling setValidationList() directly is that I can't pass parameters into the function from onreadystatechange.
See this article.
Jul 5 '07 #4
nathj
938 Expert 512MB
Heya, Nathan.



See this article.
An excellent article, that has cleared a few things up for me.

Unfortunately the code that checks the validation list array is still executing before the code called by onreadystatechange completes. It seems that the only way to the stop this is with an alert. It is a complete fudge I know, but I have learnt quite a lot through this process.

While the alert works in that it appears to prevent subsequent code from executing until the user acts it does seem to reduce accessibility a bit. Is there a better way of causing the code to wait without relying on the user?

Many thanks
Nathan
Jul 5 '07 #5
pbmods
5,821 Expert 4TB
Heya, Nathan.

While the alert works in that it appears to prevent subsequent code from executing until the user acts it does seem to reduce accessibility a bit. Is there a better way of causing the code to wait without relying on the user?
[Un]fortunately, JavaScript has no sleep() function. The only way to delay execution is to use the setTimeout() function.
Jul 5 '07 #6
nathj
938 Expert 512MB
Heya, Nathan.



[Un]fortunately, JavaScript has no sleep() function. The only way to delay execution is to use the setTimeout() function.
Hi pbmods,

First, thanks for all the help so far.

I tried to play around with the setTimeout() function and couldn't get this to work. What I tried was:
Expand|Select|Wrap|Line Numbers
  1. var lnTime = setTimeOut(setValidationList(pnListItem), 3000);
  2.  
I must admit I didn't really understand what I was doing I was simply following some instructions I had seen some place on the web. I do prefer to understand why and how something works.

Cheers
Nathan
Jul 5 '07 #7
pbmods
5,821 Expert 4TB
Heya, Nathan.

Expand|Select|Wrap|Line Numbers
  1. var lnTime = setTimeOut(setValidationList(pnListItem), 3000);
  2.  
I must admit I didn't really understand what I was doing I was simply following some instructions I had seen some place on the web. I do prefer to understand why and how something works.
setTimeout() takes two arguments: An object to be evaluated and a number that represents the number of milliseconds to wait before evaluating the object.

Since JavaScript will try to execute setValidationList(), you have to instead create an anonymous function and pass that to setTimeout():
Expand|Select|Wrap|Line Numbers
  1. var lnTime = setTimeOut(function() { setValidationList(pnListItem); }, 3000);
  2.  
  3. // Or spaced out, if you prefer....
  4. var lnTime = setTimeOut(
  5.     function() {
  6.         setValidationList(pnListItem);
  7.     },
  8.     3000);
  9.  
After 3000 milliseconds, the browser will evaluate the function that you created, which executes setValidationList(). Note that this will only work properly if your AJAX call returns within 3 seconds.
Jul 5 '07 #8
nathj
938 Expert 512MB
Heya, Nathan.



setTimeout() takes two arguments: An object to be evaluated and a number that represents the number of milliseconds to wait before evaluating the object.

Since JavaScript will try to execute setValidationList(), you have to instead create an anonymous function and pass that to setTimeout():
Expand|Select|Wrap|Line Numbers
  1. var lnTime = setTimeOut(function() { setValidationList(pnListItem); }, 3000);
  2.  
  3. // Or spaced out, if you prefer....
  4. var lnTime = setTimeOut(
  5.     function() {
  6.         setValidationList(pnListItem);
  7.     },
  8.     3000);
  9.  
After 3000 milliseconds, the browser will evaluate the function that you created, which executes setValidationList(). Note that this will only work properly if your AJAX call returns within 3 seconds.
Hi pbmods,

I gotta say I really appreciate you taking the time to help. I have played around with this function, and thanks to your explanation i actually have a better understanding of what I am doing and how and why it should work.

I have spent some time messing around with this idea of delaying code execution and finally decided that I don't really like the idea. So, As I need to do something like that I figure user information is the best way forward, this leaves me with the alert to inform the user what is happening at this stage.

This solution still seems like a bit of a fudge to me but hopefully it wont look out of place when the site goes live (probably next year).

What do you think of this solution? I respect your opinion and if you woudl be good enough to spare the time to share it I'd really appreciate it.

Once again many thanks
Nathan
Jul 5 '07 #9
pbmods
5,821 Expert 4TB
Heya, Nathan.

The problem with delaying your code's execution (whether by using a timer or by using an alert) is that you don't really know when your AJAX call returns. Ideally, if you get a response sooner, you'll want to display the results sooner.

As you're aware, you can accomplish this by using http's onreadystatechange handler. But what if (as you mentioned) you need to pass extra arguments or call additional functions?

Check out your setTimeout call:
Expand|Select|Wrap|Line Numbers
  1. var lnTime = setTimeOut(
  2.     function() {
  3.         setValidationList(pnListItem);
  4.     },
  5.     3000);
You can use the same principle when you set goXMLHTTP.onreadystatechange in validateItem() (line 68 in your OP):
Expand|Select|Wrap|Line Numbers
  1. goXMLHTTP.onreadystatechange=function() {
  2.     writeResponse();
  3.     setValidationList(pnListItem);
  4. };
Jul 5 '07 #10
nathj
938 Expert 512MB
Heya, Nathan.

The problem with delaying your code's execution (whether by using a timer or by using an alert) is that you don't really know when your AJAX call returns. Ideally, if you get a response sooner, you'll want to display the results sooner.

As you're aware, you can accomplish this by using http's onreadystatechange handler. But what if (as you mentioned) you need to pass extra arguments or call additional functions?

Check out your setTimeout call:
Expand|Select|Wrap|Line Numbers
  1. var lnTime = setTimeOut(
  2.     function() {
  3.         setValidationList(pnListItem);
  4.     },
  5.     3000);
You can use the same principle when you set goXMLHTTP.onreadystatechange in validateItem() (line 68 in your OP):
Expand|Select|Wrap|Line Numbers
  1. goXMLHTTP.onreadystatechange=function() {
  2.     writeResponse();
  3.     setValidationList(pnListItem);
  4. };
Thank you so much. I really appreciate this, you are truly a star! I have now got this to behave as I want it without any dodgy alerts or unecessary waiting around. This has made my day. I couldn't have done it without your help.

More importantly than it working is the fact that I know understand why it works. This is always my ultimate aim, so a real big thnkyou for that too.
Cheers
Nathan
Jul 6 '07 #11
pbmods
5,821 Expert 4TB
Heya, Nathan.

That's great to hear that you were able to get it working!

Good luck with your project, and if you ever need anything, post back anytime :)
Jul 6 '07 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: jdph40 | last post by:
In Access 2002, I designed a simple database for our Safety department to enter results of a survey. There are 41 true/false statements. I have a main form called frmSurvey with a subform called...
19
by: C# Learner | last post by:
What's a nice way to create a non-blocking pause in execution? Will I need to use some kind of timer for this, or is there a nicer way?
8
by: Wim | last post by:
My GUI application starts a process (a console program) when the user hits Play. I would like to add an option to pause that process. The code I've added to detect if the user hit pause/unpause...
6
by: Mark Broadbent | last post by:
Firstly I am not after a programatic solution (e.g. Console.ReadLine() or a Loop construct). I am trying to find an option in the IDE to pause on exit. For instance with the SharpDevelop IDE...
2
by: Dave | last post by:
I have a program that I need the program to temporarly stop and wait for a response from a piece of equipment. After a set period I want the program to continue. Like below --execute lline...
11
by: Paul Mars | last post by:
How to pause in the middle of a sub? I can not use a timer. The Sub can not be broken in two. tx, paul
0
by: Arik | last post by:
Hi, I would like to disable the 'Pause/Break' key in a console application. Normally, pressing the 'Pause' key halts the application's execution and may lead to undesirable processing gaps in my...
18
by: Frank | last post by:
I'm using Sleep(100) and that works OK. However, it would be better if my app continued to receive and process keyboard messages. How can I pause the execution of code in one routine while...
0
by: steveyjg | last post by:
I'm trying to call a function that will pause execution for 30 seconds and have a counter timer counting to 30 seconds during this pause. When the counter hits 30 execution of the program will...
1
by: desktop | last post by:
Is there someway to pause the execution of a program? I have a large while loop and before it gets started I would like to pause the program so I can see the output before it gets overwritten by...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
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,...
0
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...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.