Link to home
Start Free TrialLog in
Avatar of th_c_man
th_c_man

asked on

Can someone explain setTimeOut()

Can someone explain setTimeOut and realted functions such as clearTimeOut and whatever. How to use them, what they do, syntax etc.
Avatar of kmartin7
kmartin7
Flag of United States of America image

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
>Availability

>Navigator 2.0, Internet Explorer 3.0

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

Kurt
Avatar of Michel Plungjan
And  there is a comparable setInterval in those browsers too ;-)

Michel
Avatar of th_c_man
th_c_man

ASKER

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
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)

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

Michel
Has your question been answered to your liking?
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.
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.
ASKER CERTIFIED SOLUTION
Avatar of kmartin7
kmartin7
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Answer is above...
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>
I'll take a look at it tomorrow night...I gotta get some sleep tonight.

Kurt
ok, thanx

Daniel
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
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
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
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 :)
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.