Solved

Can someone explain setTimeOut()

Posted on 1999-01-06
19
559 Views
Last Modified: 2011-09-20
Can someone explain setTimeOut and realted functions such as clearTimeOut and whatever. How to use them, what they do, syntax etc.
0
Comment
Question by:th_c_man
  • 9
  • 7
  • 2
  • +1
19 Comments
 
LVL 11

Expert Comment

by:kmartin7
Comment Utility
From JavaScript: The Defintive Guide:

Name

Window.setTimeout() Method---defer execution of code

Availability

Navigator 2.0, Internet Explorer 3.0

Synopsis

window.setTimeout(code, delay)

Arguments

code

A string that contains the JavaScript code to be executed after the delay has elapsed.

delay

The amount of time, in milliseconds, before the JavaScript statements in the string code should be executed.

Returns

An opaque value (a "timeout id") that can be passed to the clearTimeout() method to cancel the execution of code.

Description

The setTimeout() method defers the execution of the JavaScript statements in the string code for delay milliseconds.
Once the specified number of milliseconds have elapsed, the statements in code are executed normally. Note that they are executed only once. To execute code repeatedly, code must itself contain a call to setTimeout() to register itself to be executed again.

The statement in the string code are executed in the context of window--i.e., window will be the current window for those statements. If more than one statement appears in code, the statements must be separated from each other with semicolons.

Bugs

In Navigator 2.0 memory allocated by JavaScript is not freed until the browser leaves a web page. Each call to setTimeout() consumes some memory, and the deferred code generally consumes memory as well. Thus, if a page performs some sort of infinite loop (for example, a status-bar animation using Window.setTimeout() and Window.status),
then memory will slowly be consumed, and Navigator may crash if the user remains on the page for a long time.

---------

Name

Window.clearTimeout() Method---cancel deferred execution

Availability

Navigator 2.0, Internet Explorer 3.0

Synopsis

window.clearTimeout(timeoutId)

Arguments

timeoutId

A value returned by setTimeout() that identifies the timeout to be cancelled.

Returns

Nothing.

Description

The clearTimeout() method cancels the execution of code that has been deferred with the setTimeout() method. The timeoutId argument is a value returned by the call to setTimeout() and identifies which (of possibly more than one) block of deferred code to cancel.

Kurt
0
 
LVL 11

Expert Comment

by:kmartin7
Comment Utility
>Availability

>Navigator 2.0, Internet Explorer 3.0

I should have added that this is still available in today's DHTML browsers.

Kurt
0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
And  there is a comparable setInterval in those browsers too ;-)

Michel
0
 

Author Comment

by:th_c_man
Comment Utility
ok. I'm writing a clock ( i know ther is one in official documentation somewhere but i want the experience of writing it, not the clock itself)

if i have a

function keepTime(){
  while (running){
    var now = new Date();
    var h = now.getHours();
    var m = now.getMinutes();
    var s = now.getSeconds();
    showTime(h,m,s);
    setTimeOut(keepTime(),1000);
  }
}

and a function showTime(h,m,s) which writes the time to a form input field, will this code work?

running is a boolean variable defined earlyer in the code.

i have a method stopClock() which sets running to false, theoretically stopping execution of the clock, and this is called in onUnload() in the body.

i have several other functions that decide this and that and the other to make sure the clock works properly and so on but i figured this was all i needed to give you the idea.

daniel
0
 
LVL 6

Expert Comment

by:PBall
Comment Utility
the code is solid enough, except for the setTimeout line.

it's setTimeout and not setTimeOut and it should be called like this:

setTimeout("keepTime()",1000)

0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
Also be careful with onUnload since many browsers 'forget' properties the the document they unload so running might not exist at that time....

Michel
0
 
LVL 11

Expert Comment

by:kmartin7
Comment Utility
Has your question been answered to your liking?
0
 

Author Comment

by:th_c_man
Comment Utility
Yeh, I think so. I know what im doing now so i suppose it has, thanx.

I think kmartin7's comment was the most informative, thanx also pball, otherwise i wouldnt have been able to use it without further stuffing around.

Post an answer kmartin7, and i'll give you the points.
0
 

Author Comment

by:th_c_man
Comment Utility
Yeh, I think so. I know what im doing now so i suppose it has, thanx.

I think kmartin7's comment was the most informative, thanx also pball, otherwise i wouldnt have been able to use it without further stuffing around.

Post an answer kmartin7, and i'll give you the points.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 11

Accepted Solution

by:
kmartin7 earned 50 total points
Comment Utility
;-0
0
 
LVL 11

Expert Comment

by:kmartin7
Comment Utility
Answer is above...
0
 

Author Comment

by:th_c_man
Comment Utility
I tried all this and my clock doesn't seem to work. I was calling it with the arguments in the incorrect order. I fixed tht up and i'm now getting a too many javascript errors message. I dont have the time at the moment to debu my script. Can someone have a look at it?? It is

<html>
<head>
<script>
<!--
var gRunning = false;

function startClock(){
  if(gRunning) stopClock();
  gRunning = true;
  keepTime();
}

function keepTime(){
  while(gRunning){
    var now=new Date();
    var h = now.getHours();
    var m = now.getMinutes();
    var s = now.getSeconds();
    showTime(h,m,s);
    setTimeout("keepTime()",1000);
  }
}

function stopClock(){
  if(gRunning)
    gRunning=false;
}

function showTime(h,m,s){
  var time=""
  if(h>9) time +=(h+":");
  else time+=(" "+h+":");
  if(m>9) time +=(m+":");
  else time +=("0"+m+":");
  if(s>9) time +=s;
  else  time+=(" "+s);
  document.Clock.screen.value=time;
}

//-->
</script>
<body>
<form name="Clock">
<Input Type="text" name="screen" value="        ">
<Script>
<!--
startClock();
//-->
</Script>

</form>
</body>
0
 
LVL 11

Expert Comment

by:kmartin7
Comment Utility
I'll take a look at it tomorrow night...I gotta get some sleep tonight.

Kurt
0
 

Author Comment

by:th_c_man
Comment Utility
ok, thanx

Daniel
0
 
LVL 11

Expert Comment

by:kmartin7
Comment Utility
I really didn't know what was going on with your script - and I am quite busy at work to debug, so I modified your script with a method I am more familiar with:

<html>
<head>
<script language="JavaScript">

<!-- begin cloaking device
var keepTime = null
var gRunning = false

function stopClock(){
   if(gRunning) {
      clearTimeout(keepTime);
      gRunning = false;
      }
}

function startClock(){
    stopClock();
    runClock();
}

function runClock(){
        document.clock.screen.value = showTime();
        keepTime = setTimeout("runClock()",1000);
        gRunning = true;
}
function showTime() {
        now = new Date();
        h = now.getHours();
        m = now.getMinutes();
        s = now.getSeconds();
        time = "" + ((h < 12) ? ":0" : "") + h;
        time  += ((m < 10) ? ":0" : ":") + m;
        time  += ((s < 10) ? ":0" : ":") + s;
        return time;
}

// end cloaking device-->

</script>
</head>
<body onLoad="startClock();" onUnload="stopClock();">
<form name="clock">
<input type="text" size="11" name="screen"></p>
</form>
</body>
</html>

Kurt
0
 

Author Comment

by:th_c_man
Comment Utility
This is the one from the netscape documentation with the variable names changed to mirror my ones, isn't it??

I'll use that one i s'pose, and give ya the points and debug my own when ive got time :)

Daniel
0
 
LVL 11

Expert Comment

by:kmartin7
Comment Utility
I was actually using this script to help debug yours, but could not figure out why yours kept cycling the setTimeout on yours.  It was frustrating me so much, I just gave up.  This is what was left (using your naming convention) of the method I was using for debugging purposes.  Is it from the Netscape site?  I have it in an archive directory of scripts is use to learn from, but I don't think I got it from Netscape...

Maybe if I can get some free time in the next week I will take a look at your again.  I think a fresh look at it may help...

Kurt
0
 

Author Comment

by:th_c_man
Comment Utility
Thanx..

BTW: if you change the line that reads
      <input type="text" size="11" name="screen"></p>
to read
      <input type="button" value=&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; name="screen"></p>

You get the clock displayed on a button face instead of in a text field :)
0
 
LVL 11

Expert Comment

by:kmartin7
Comment Utility
Cool.  Frankly I prefer the button or status bar to display the clock rather than a text field. The text field usually draws too much attention to itself unless your background is white.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now