Solved

Can someone explain setTimeOut()

Posted on 1999-01-06
19
563 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
ID: 1276427
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
ID: 1276428
>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
ID: 1276429
And  there is a comparable setInterval in those browsers too ;-)

Michel
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:th_c_man
ID: 1276430
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
ID: 1276431
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
ID: 1276432
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
ID: 1276433
Has your question been answered to your liking?
0
 

Author Comment

by:th_c_man
ID: 1276434
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
ID: 1276435
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
 
LVL 11

Accepted Solution

by:
kmartin7 earned 50 total points
ID: 1276436
;-0
0
 
LVL 11

Expert Comment

by:kmartin7
ID: 1276437
Answer is above...
0
 

Author Comment

by:th_c_man
ID: 1276438
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
ID: 1276439
I'll take a look at it tomorrow night...I gotta get some sleep tonight.

Kurt
0
 

Author Comment

by:th_c_man
ID: 1276440
ok, thanx

Daniel
0
 
LVL 11

Expert Comment

by:kmartin7
ID: 1276441
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
ID: 1276442
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
ID: 1276443
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
ID: 1276444
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
ID: 1276445
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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…

837 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