Monday, November 21, 2005

Creating Time Delays withing your CFM pages

Well, this is my second post and I thought it would be a good one to share. I needed to find a way to cause a user's browser to be redirected upon a certain time and in my search I found 2 useful ways to tackle this task. The first is client-side and the second-one is server side.

Client-Side
For the client-side solution I used the following javascript method: window.setTimeOut(expression/function,milliseconds)

This method is used to call a function or evaluate an expression after a specified number of milliseconds. If an expression is to be evaluated, it must be quoted to prevent it being evaluated immediately. Note that the use of this method does not halt the execution of any remaining scripts until the timeout has passed, it just schedules the expression or function for the specified time.

The following example redirects the current window and uses the setTimeout method to call the reloc() function which relocates it after five seconds (5000 milliseconds)

 function reloc(){
location='urlToGoHere'; } self.document.write("This window will redirect automatically after \ five seconds. Thanks for your patience"); self.setTimeout('reloc()', 5000);

Server-Side
Excerpt from Ben Forta's Advanced CFMX 7 Application Development
For the server-side solution I took advantage of the underlying Java platform available to Coldfusion.

The Java API defines a "thread" class that has a method allowing you to make the currently executing thread "sleep" (temporarily cease execution) for a specified number of milliseconds. That method is perfect if you need to cause a delay withing a cfm page. To call it all you have to do is this:

<cfobject type="java" action="create" class="java.lang.Thread"  name="thread" />
OR 
<cfset thread=CreateObject("java","java.lang.Thread")/>
Then to simply call the class and its method, you can do this:
<cfset thread.sleep(5000)/>
The only problem I had with the solution above is that for some reason cflocation did not work after placing the thread to sleep. Even though other coldfusion actions such as a cfoutput or loop worked the cflocation did not. I will investigate this more, but for now the non-working and working example is below.
// NON - WORKING
<cfobject type="java" action="create" class="java.lang.Thread"  name="thread" />
<cfset thread.sleep(5000)>

 >cflocation addtoken="no" url="urlToGoHere" <

// WORKING 
<cfobject type="java" action="create" class="java.lang.Thread"  name="thread" />
<cfset thread.sleep(5000)>

 <script language="javascript">
 location='urlToGoHere';
 </script>
Eventhough these examples are simple and only use a redirection method I am sure you can find more ways to use them. The main difference between using client or server side is, what action needs to occur, a client or server side. I hope this was informational to some as it was to me.

JC

No comments:

Post a Comment