please help me with this program...badly needed....

You need to show us some afford from your side first (some implemented code). I could do it but I feel that this is your assignment from school, so I should not spoil your learning.

You need to show us some afford from your side first (some implemented code). I could do it but I feel that this is your assignment from school, so I should not spoil your learning.

here some code

<BODY>

<center>
<table border=8 bgcolor=white width=60% cellspacing=0>
<tr><td>
<center>
<h2>Hangman!</h2><br>
<b><h3><font color=red>Topic:</font>  
Presidents of The United States</h3></b>
<hr><br>

<SCRIPT LANGUAGE="JavaScript">


<!-- Begin
function getCookie (name) {
var dcookie = document.cookie;
var cname = name + "=";
var clen = dcookie.length;
var cbegin = 0;
while (cbegin < clen) {
var vbegin = cbegin + cname.length;
if (dcookie.substring(cbegin, vbegin) == cname) {
var vend = dcookie.indexOf (";", vbegin);
if (vend == -1) vend = clen;
return unescape(dcookie.substring(vbegin, vend));
}
cbegin = dcookie.indexOf(" ", cbegin) + 1;
if (cbegin == 0) break;
}
return null;
}
function setCookie (name, value, expires) {
if (!expires) expires = new Date();
document.cookie = name + "=" + escape (value) + "; expires=" + expires.toGMTString() +  "; path=/";
}
function delCookie (name) {
var expireNow = new Date();
document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT" +  "; path=/";
}
var Alphabet = new initAlphaArray()
var NumOfWords = 42;
var SaveData = "";
var ImageNum = "";
var LettersSelected = "";
var RandomWord = "";
var DisplayWord = "";
var position = 0;
var word = new WordList();
var expdate = new Date();
var RandomNumber = (expdate.getSeconds())%NumOfWords;
function initAlphaArray() {
this.length = 26
this[0] = "A"
this[1] = "B"
this[2] = "C"
this[3] = "D"
this[4] = "E"
this[5] = "F"
this[6] = "G"
this[7] = "H"
this[8] = "I"
this[9] = "J"
this[10] = "K"
this[11] = "L"
this[12] = "M"
this[13] = "N"
this[14] = "O"
this[15] = "P"
this[16] = "Q"
this[17] = "R"
this[18] = "S"
this[19] = "T"
this[20] = "U"
this[21] = "V"
this[22] = "W"
this[23] = "X"
this[24] = "Y"
this[25] = "Z"
}
function WordList() {
this.length = NumOfWords;
this[0] = "GEORGE WASHINGTON";
this[1] = "JOHN ADAMS";
this[2] = "THOMAS JEFFERSON";
this[3] = "JAMES MADISON";
this[4] = "JAMES MONROE";
this[5] = "JOHN QUINCY ADAMS";
this[6] = "ANDREW JACKSON";
this[7] = "MARTIN VAN BUREN";
this[8] = "WILLIAM HENRY HARRISON";
this[9] = "JOHN TYLER";
this[10] = "JAMES POLK";
this[11] = "ZACHARY TAYLOR";
this[12] = "MILLARD FILLMORE";
this[13] = "FRANKLIN PIERCE";
this[14] = "JAMES BUCHANAN";
this[15] = "ABRAHAM LINCOLN";
this[16] = "ANDREW JOHNSON";
this[17] = "ULYSSES GRANT";
this[18] = "RUTHERFORD HAYES";
this[19] = "JAMES GARFIELD";
this[20] = "CHESTER ARTHUR";
this[21] = "GROVER CLEVELAND";
this[22] = "BENJAMIN HARRISON";
this[23] = "GROVER CLEVELAND";
this[24] = "WILLIAM MCKINLEY";
this[25] = "THEODORE ROOSEVELT";
this[26] = "WILLIAM HOWARD TAFT";
this[27] = "WOODROW WILSON";
this[28] = "WARREN HARDING";
this[29] = "CALVIN COOLIDGE";
this[30] = "HERBERT HOOVER";
this[31] = "FRANKLIN ROOSEVELT";
this[32] = "HARRY TRUMAN";
this[33] = "DWIGHT EISENHOWER";
this[34] = "JOHN KENNEDY";
this[35] = "LYNDON JOHNSON";
this[36] = "RICHARD NIXON";
this[37] = "GERALD FORD";
this[38] = "JIMMY CARTER";
this[39] = "RONALD REAGAN";
this[40] = "GEORGE BUSH";
this[41] = "BILL CLINTON";
}
function availableLetters(i) {
if (LettersSelected.charAt(i)==Alphabet[i])
document.write('<TD ALIGN=CENTER VALIGN=CENTER WIDTH=20 HEIGHT=12>' +
'<B><A HREF="javascript:LoadNextPage('+i+',\''+Alphabet[i]+
'\')">'+Alphabet[i]+'</A></B></TD>');
else
document.write('<TD ALIGN=CENTER VALIGN=CENTER WIDTH=20 HEIGHT=12> </TD>');
}
function LoadNextPage(selected,letter) {
var j=0;
var HoldLettersSelected = LettersSelected;
LettersSelected = "";
if (selected == 0) {
for (j=1; j<=25; j++) {
LettersSelected += HoldLettersSelected.charAt(j);
}
LettersSelected = "^" + LettersSelected;
}
else if (selected == 25) {
for (j=0; j<=24; j++) {
LettersSelected += HoldLettersSelected.charAt(j);
}
LettersSelected += "^";
}
else {
for (j=0; j<selected; j++)
{
LettersSelected += HoldLettersSelected.charAt(j);
}
LettersSelected += "^";
for (j=selected+1; j<=25; j++) {
LettersSelected += HoldLettersSelected.charAt(j);
   }
}


SaveData = ImageNum + LettersSelected + RandomWord + "*";
setCookie("_HangMan", SaveData, expdate);
history.go(0);
}

// Sets a cookie that will expire in 10 days

expdate.setTime (expdate.getTime() + (1000*60*60*24*10));
if(getCookie("_HangMan") == null)
{
ImageNum = "A";
LettersSelected = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
RandomWord = word[RandomNumber];
SaveData = ImageNum + LettersSelected + RandomWord + "*";
setCookie("_HangMan", SaveData, expdate);
}
else {
SaveData = getCookie("_HangMan");
ImageNum = SaveData.charAt(0);
for (position=1; position<=26; position++) {
LettersSelected += SaveData.charAt(position);
}
for (position=27; position<SaveData.indexOf("*"); position++) {
RandomWord += SaveData.charAt(position);
   }
}
DisplayWord = "";
for (i=0; i<RandomWord.length; i++) {
if (RandomWord.charAt(i) == ' ') {
DisplayWord += " "; 
}
else {
MatchFound = false;
for (j=0; j<=25; j++) {
if ((LettersSelected.charAt(j) == "^") && (RandomWord.charAt(i) == Alphabet[j])) {
DisplayWord += RandomWord.charAt(i);
MatchFound = true;
   }
}
if (!MatchFound) DisplayWord += "-";
   }
}
if (ImageNum == "J") {
document.write('<font color=red size=4>You Lost!<br>Answer:  "' + RandomWord + '"</font>');
}
else if (RandomWord == DisplayWord) {
document.write('<font color=red size=8>You Win!</font>');
}
else {
document.write('<table>');
document.write('<tr>');
for (i=0; i<13; i++) availableLetters(i);
document.write('</tr>');
document.write('<tr>');
for (i=13; i<26; i++) availableLetters(i);
document.write('</tr>');
document.write('</table>');
}
document.write('<br>');
document.write('<br>');
document.write('<font size=9><tt>');
document.write(DisplayWord);
document.write('</tt></font>');
document.write('<form>');
document.write('<input type="button" VALUE="New Game"'+
'onClick="delCookie(\'_HangMan\');history.go(0);">');
document.write('</form>');
document.write('</center>');
// End -->
</SCRIPT>
</td></tr>
</table>
</center>

</BODY>
<!-- Script Size:  6.31 KB  -->

my question is how can i put a timer in this game and a clue that the player may know who will be the person they are guessing..can you help me??...

Glad to see that you have done your homework. I would suggest one thing that you should not do all display part using JavaScript. It is not a good idea and it will become more difficult to maintain & update.

I modified your code by keeping some and add some. Below is the sample code that could be rendered on Firefox/Chrome. I am not sure about IE but it should work on the browser as well (didn't test). The way I deal with image display is to use CSS and display it as background image. You could change to whatever you like actually.

For timer, setTimeout() function is required in order to wait for a fixed period of time before the clock tick again. You can use the function to do any even that need to stop & go. Anyway, hope this help.

<html>
<head>
<style type="text/css">
.all_display {
  border-left:8px solid lightgray;
  border-top:8px solid darkgray;
  border-right:8px solid #505050;
  border-bottom:8px solid #505050;
  background-color:white;
  width:60%;
  margin-left:20%;
}
.inner_tablecell {
  font-size: 14px;
  font-weight: bold;
  text-align: center;
  width: 12px;
}
.fake_link {
  color: blue;
  font-weight: bold;
  text-decoration: underline;
  cursor: hand;
  cursor: pointer;
}
.img1 {
  background-image: url("imgs/imageA.jpg");
  background-repeat: no-repeat;
}
.img2 {
  background-image: url("imgs/imageB.jpg");
  background-repeat: no-repeat;
}
.img3 {
  background-image: url("imgs/imageC.jpg");
  background-repeat: no-repeat;
}
.img4 {
  background-image: url("imgs/imageD.jpg");
  background-repeat: no-repeat;
}
.img5 {
  background-image: url("imgs/imageE.jpg");
  background-repeat: no-repeat;
}
.img6 {
  background-image: url("imgs/imageF.jpg");
  background-repeat: no-repeat;
}
.img7 {
  background-image: url("imgs/imageG.jpg");
  background-repeat: no-repeat;
}
.img8 {
  background-image: url("imgs/imageH.jpg");
  background-repeat: no-repeat;
}
.img9 {
  background-image: url("imgs/imageI.jpg");
  background-repeat: no-repeat;
}
.img10 {
  background-image: url("imgs/imageJ.jpg");
  background-repeat: no-repeat;
}
</style>

<script type="text/javascript">
var NumOfWords = 42;
var selectedWord
var timerID

function WordList() {
  this.length = NumOfWords;
  this[0] = ["GEORGE WASHINGTON", "hint description"];
  this[1] = ["JOHN ADAMS", "hint description"];
  this[2] = ["THOMAS JEFFERSON", "hint description"];
  this[3] = ["JAMES MADISON", "hint description"];
  this[4] = ["JAMES MONROE", "hint description"];
  this[5] = ["JOHN QUINCY ADAMS", "hint description"];
  this[6] = ["ANDREW JACKSON", "hint description"];
  this[7] = ["MARTIN VAN BUREN", "hint description"];
  this[8] = ["WILLIAM HENRY HARRISON", "hint description"];
  this[9] = ["JOHN TYLER", "hint description"];
  this[10] = ["JAMES POLK", "hint description"];
  this[11] = ["ZACHARY TAYLOR", "hint description"];
  this[12] = ["MILLARD FILLMORE", "hint description"];
  this[13] = ["FRANKLIN PIERCE", "hint description"];
  this[14] = ["JAMES BUCHANAN", "hint description"];
  this[15] = ["ABRAHAM LINCOLN", "hint description"];
  this[16] = ["ANDREW JOHNSON", "hint description"];
  this[17] = ["ULYSSES GRANT", "hint description"];
  this[18] = ["RUTHERFORD HAYES", "hint description"];
  this[19] = ["JAMES GARFIELD", "hint description"];
  this[20] = ["CHESTER ARTHUR", "hint description"];
  this[21] = ["GROVER CLEVELAND", "hint description"];
  this[22] = ["BENJAMIN HARRISON", "hint description"];
  this[23] = ["GROVER CLEVELAND", "hint description"];
  this[24] = ["WILLIAM MCKINLEY", "hint description"];
  this[25] = ["THEODORE ROOSEVELT", "hint description"];
  this[26] = ["WILLIAM HOWARD TAFT", "hint description"];
  this[27] = ["WOODROW WILSON", "hint description"];
  this[28] = ["WARREN HARDING", "hint description"];
  this[29] = ["CALVIN COOLIDGE", "hint description"];
  this[30] = ["HERBERT HOOVER", "hint description"];
  this[31] = ["FRANKLIN ROOSEVELT", "hint description"];
  this[32] = ["HARRY TRUMAN", "hint description"];
  this[33] = ["DWIGHT EISENHOWER", "hint description"];
  this[34] = ["JOHN KENNEDY", "hint description"];
  this[35] = ["LYNDON JOHNSON", "hint description"];
  this[36] = ["RICHARD NIXON", "hint description"];
  this[37] = ["GERALD FORD", "hint description"];
  this[38] = ["JIMMY CARTER", "hint description"];
  this[39] = ["RONALD REAGAN", "hint description"];
  this[40] = ["GEORGE BUSH", "hint description"];
  this[41] = ["BILL CLINTON", "hint description"];
  this[42] = ["BARACK OBAMA", "hint description"];
}

function startGame(alphabetElementID, wordElementID, hintElementID, timerElementID, graphicElementID) {
  displayAlphabet(alphabetElementID, wordElementID, graphicElementID)
  displayRandomWord(wordElementID, hintElementID)
  displayTimer(timerElementID, 1)  // reset timer
  displayGraphic(graphicElementID, 1)
  displayTimer(timerElementID, 0)  // run timer
}  // startGame(string, string, string, string, string, string)

// create display using DOM technique
function displayAlphabet(displayElementID, awordElementID, graphicElementID) {
  var dElem = document.getElementById(displayElementID)
  if (dElem) {  // display element exists
    if (dElem.getElementsByTagName("table").length>0) {  // table exists already
      var alphabetTable = dElem.getElementsByTagName("table")[0]  // expect only 1 table
      for (var row=0; row<alphabetTable.rows.length; row++) {
        for (var col=0; col<alphabetTable.rows[row].cells.length; col++) {
          var content = alphabetTable.rows[row].cells[col].style.visibility = null
        }
      }
    }
    else {  // not have table yet, create it
      var alp
      var newTab = document.createElement("table")
      newTab.style.width = "60%"
      newTab.style.marginLeft = "20%"
      var newTr1 = newTab.insertRow(0)  // first row
      for (var i=65; i<78; i++) {  // display A-M
        alp = String.fromCharCode(i)
        var newTd = newTr1.insertCell(i-65)  // each table cell in 1st row
        var arg = "'"+alp+"','"+displayElementID+"','"+awordElementID+"','"+graphicElementID+"'"
        newTd.className = "inner_tablecell"
        newTd.onclick = function() { chooseAlphabet(this, displayElementID, awordElementID, graphicElementID) }
        var tdCont = document.createElement("span")
        tdCont.className = "fake_link"
        tdCont.innerHTML = alp
        newTd.appendChild(tdCont)
      }
      var newTr2 = newTab.insertRow(1)  // first row
      for (var i=78; i<91; i++) {  // display A-M
        alp = String.fromCharCode(i)
        var newTd = newTr2.insertCell(i-78)  // each table cell in 2nd row
        newTd.className = "inner_tablecell"
        newTd.onclick = function() { chooseAlphabet(this, displayElementID, awordElementID, graphicElementID) }
        var tdCont = document.createElement("span")
        tdCont.className = "fake_link"
        tdCont.innerHTML = alp
        newTd.appendChild(tdCont)
      }
      dElem.appendChild(newTab)
    }
  }
}  // displayAlphabet(string, string, string)

// create display using string which is assigned to innerHTML
function displayRandomWord(displayElementID, hintElementID) {
  selectedWord = (new WordList())[Math.floor(Math.random()*NumOfWords)]
  var dElem = document.getElementById(displayElementID)
  var hElem = document.getElementById(hintElementID)
  if (dElem) {  // display element exists
    var out = "<table style=\"width:60%;margin-left:20%\"><tr>\n"
    for (var i=0; i<selectedWord[0].length; i++) {
      out += "<td class=\"inner_tablecell\">"
      out += (selectedWord[0].charAt(i)==" ")? "&nbsp;" : "_"
      out += "</td>\n"
    }
    out += "</tr></table>"
    dElem.innerHTML = out
  }
  if (hElem) {  // hint element exists
    hElem.innerHTML = selectedWord[1]
  }
}  // displayRandomWord(string)

function displayTimer(timerElementID, reset) {
  var dElem = document.getElementById(timerElementID)
  if (dElem) {
    if (!isNaN(reset) && reset>0) {
      dElem.innerHTML = "00:00:00"  // reset value
    }
    else {
      var time = dElem.innerHTML.split(":")
      if (time.length==3) {  // somewhat valid size
        // ensure to integer
        time[0] = parseInt(time[0],10)
        time[1] = parseInt(time[1],10)
        time[2] = parseInt(time[2],10)
        time[2] += 1  // increase by 1 second
        time[1] += Math.floor(time[2]/60)  // add second to minute
        time[0] += Math.floor(time[1]/60)  // add minute to hour
        time[2] = time[2]%60  // adjust second
        time[1] = time[1]%60  // adjust minute
        var timeStr = time[0]+":"  // hour
        timeStr += (time[1]<10)? ("0"+time[1]) : time[1]  // add '0' if minute is less than 10
        timeStr += ":"
        timeStr += (time[2]<10)? ("0"+time[2]) : time[2]  // add '0' if second is less than 10
        dElem.innerHTML = timeStr
        // wait 1000 milliseconds before display the time again
        timerID = window.setTimeout("displayTimer('"+timerElementID+"', 0)", 1000)
      }
    }
  }
}  // displayTimer(string)

function displayGraphic(graphicElementID, reset) {
  var dElem = document.getElementById(graphicElementID)
  if (dElem) {  // graphic element exists
    var img = dElem.getElementsByTagName("div")[0]
    if (!isNaN(reset) && reset>0) {  // reset
      img.className = "img1"
    }
    else {
      var i = parseInt(img.className.replace("img",""),10)
      img.className = "img"+(i+1)
    }  // either reset or move the image to the back
  }  // element exists
}  // displayGraphic(string, int)

function chooseAlphabet(tdElement, alphabetElementID, awordElementID, graphicElementID) {
  if (selectedWord) {
    if (tdElement && !tdElement.style.visibility) {  // non-selected alphabet table cell
      var alphabet = tdElement.getElementsByTagName("span")[0].innerHTML
      var wElem = document.getElementById(awordElementID)
      var wTab = wElem.getElementsByTagName("table")[0]  // expect 1 table
      var correct = false
      var done
      for (var i=0; i<selectedWord[0].length; i++) {
        if (selectedWord[0].charAt(i)==alphabet) {
          wTab.rows[0].cells[i].innerHTML = selectedWord[0].charAt(i)
          correct = true
          done = isDone(wTab.rows[0])
          if (done) {
            break
          }
        }
      }
      tdElement.style.visibility = "hidden"
      if (done) {
        alert("You WIN!!!")
        selectedWord = null
        stopTimer()
      }
      else if (!correct) {
        displayGraphic(graphicElementID)
        if (isOver(graphicElementID)) {
          alert("You LOSE! Try again...")
          selectedWord = null
          stopTimer()
        }
      }
    }
  }
  else {
    alert("Please start a new game first")
  }
}  // chooseAlphabet(HTMLObjectElement, string, string, string)

function isDone(trElement) {
  var res = true
  var str
  for (var i=trElement.cells.length-1; i>=0; i--) {
    str = trElement.cells[i].innerHTML.toString()
    if (trElement.cells[i].innerHTML.toString()=="_") {
      res = false
      break
    }
  }

  return res
}  // isDone(HTMLObjectElement)

function isOver(graphicElementID) {
  var dElem = document.getElementById(graphicElementID)
  if (dElem) {  // graphic element exists
    var img = dElem.getElementsByTagName("div")[0]
    var imgNum = parseInt(img.className.replace("img",""),10)
    if (imgNum>=10) { return true }  // last image is 10, so it is over
  }
  return false
}  // isOver(string)

function stopTimer() {
  if (timerID) {
    window.clearTimeout(timerID)
    timerID = null
  }
}
</script>
</head>

<BODY>
<div style="width:100%;text-align:center;">
 <table class="all_display">
 <tr>
  <td style="text-align:center">
  <h2>Hangman!</h2><br>
  <h3><span style="color:red">Topic:</span> Presidents of The United States</h3>
  </td>
 </tr><tr>
  <td id="alphabet_disp">
  <!-- all alphabets are displayed here -->
  </td>
 </tr><tr>
  <td id="aword_disp" style="text-align:center">
  <!-- a random word selected from WordList is here -->
  &nbsp;
  </td>
 </tr><tr>
  <td style="text-align:center">
  <input type="button" value="New Game"
   onclick="startGame('alphabet_disp', 'aword_disp', 'hint_disp', 'timer_disp', 'graphic_disp')">
  </td>
 </tr>
 </table>

 <h3 style="color:green">Hint:</h3>
 <div id="hint_disp"></div>

 <br>
 <div id="timer_disp"></div>

 <div style="position:relative;width:100%;height:300px" id="graphic_disp">
 <div class="img1" style="position:absolute;top:0px;margin-left:40%;width:100px;height:100px"></div>
 </div>
</div>

<script type="text/javascript">
  displayAlphabet("alphabet_disp", "aword_disp", "graphic_disp")  // first display
</script>

</BODY>
</html>

Jecris,

For lots of ideas, try sticking "hangman" into Daniweb's search (top of page).

There are plenty of results, which indicate that this has been a popular exercise for some years.

Airshow

Jecris,

Pleeeeeeeeeease don't use displayTimer as written.

It will sort of work but:

  • It is prone to inaccuracy in that there is no true underlying baseline time against which elapsed time is calculated.
  • setTimeout(...., 1000) will not in itself provide a reliable timing of one second. There will be additional processing time and potential interruptions from other prcesses on users' machines. Error will accrue, always in the same direction.
  • The function is unnecessarily processor intensive in that it reads back and re-parses the rendered timer string in order to calculate the next time.

Consider this instead:

var Timer = function(timerElementID) {//contructor pattern
	var allowRun, baseTime, t;
	var timerElement = document.getElementById(timerElementID);
	if(timerElement){
		timerElement.className = 'timer';
	}
	var reset = function(){
		stop();
		baseTime = new Date();
		if(timerElement) { timerElement.innerHTML = '00:00:00'; }
	};
	var pad = function(x) { return (x<10) ? ('0' + x) : x; }
	var run = function() {
		if(timerElement) {
			clearTimeout(t);
			var diff = (new Date()) - baseTime;
			var s = Math.floor(diff/1000);
			var m = Math.floor(s/60);
			var h = Math.floor(m/60);
			timerElement.innerHTML = [pad(h), pad(m%60), pad(s%60)].join(':');
			if(allowRun) { t = setTimeout(function(){ run(); }, 500); }
		}
	};
	var start = function(){
		allowRun = 1;
		run();
	};
	var stop = function(){
		allowRun = 0;
		run();//perform a last update just in case clock has rolled over to next whole second.
	};
	reset();
	// ****************
	this.reset = reset;
	this.start = start;
	this.stop = stop;
};

Initiate with var timer = new Timer('myTimer'); .
Start with timer.start(); .
Stop with timer.stop(); .
Reset with timer.reset(); .

Whereas Timer also uses setTimeout , it only does so to cause the clock to be updated. The time that is displayed on each occasion is not dependent on the update rate. Hence we could double or halve the update frequency without affecting the overall rate at which the timer runs, and there is no accrual of error. The setTimeout should be set to 1000 ms or less to give a good impression of the seconds ticking by. I found that 500 ms works fine.

Airshow

Thank you for all the comments and some ideas that you share to me. It help me a lot…:)

I use the program that you gave, the game is ok but the timer that I mean is that the player is given only 1 minute to answer the guess word if they cannot answer it, it will prompt “You Lost” then will proceed to the next guess word. If they can guess it then it will prompt “You Win”. How can I implement this kind of function??….

I agree that setTimeout() is not reliable for exact time and my code is not optimal. I was trying to show him without thinking too much. Anyway, it is not the main purpose of his exercise; besides, if someone wants to create an accurate timer, JavaScript may not be the best option in doing so.

By the way, you could add a check for the time you want right under displaying the time. However, adding the code this way is not really a proper way of getting out from there. If you want a proper way to do, you may need to dig a little bit deeper in JavaScript (understand how the Timer is implemented). For now, if you want to just finish it, it should be suffice.

var s = Math.floor(diff/1000);
  var m = Math.floor(s/60);
  var h = Math.floor(m/60);
  timerElement.innerHTML = [pad(h), pad(m%60), pad(s%60)].join(':');

  // add the check if h==0 && m==1 && s>=0 here
  // if it is satisfied the condition above, stop the game and display the message
  // otherwise, let the if statement below run.

    if(allowRun) { t = setTimeout(function(){ run(); }, 500); }

Hi Tay,

I agree that setTimeout() is not reliable for exact time and my code is not optimal. I was trying to show him without thinking too much.

Sorry Tay, I was probably overcritical.

After posting, I ran your code and mine simultaneously and up to about ten minutes (maybe more) they didn't really drift apart.

Oddly, the two timers sometimes showed a static difference of up to a second between them. My timer was always in the lead. This is possibly due to the way the two methods were integrated into the hangman code.

Anyway, it is not the main purpose of his exercise; besides, if someone wants to create an accurate timer, JavaScript may not be the best option in doing so.

Agreed, I wouldn't trust my life to a JavaScript timer.

Jecris, I was playing around with the code last night and can give you some clues on how to implement a time limit. No time now, I'm in a real hurry .... late for work.

Airshow

Taywin, thank you for your advice hope so I can finish it this time. ;)


Airshow, it's fine you can show me next time if you have time :) thanks in advance..

Jecris,

I'm sure there must be many ways to implement a time limit. Here's one.

First, we modify Timer such that we can specify (a) the required time limit and (b) a "callback function", as arguments to timer.start. I'll do this for you as it's not particularly obvious.

Number.prototype.pad = function() { return (this<10) ? ('0' + this) : this; };

	var Timer = function(timerElementID) {//contructor pattern
		var allowRun, baseTime, t;
		var timerElement = document.getElementById(timerElementID);
		if(timerElement){ timerElement.className = 'timer'; }
		var run = function(limit, callbackFn) {
			if(timerElement) {
				clearTimeout(t);
				var diff = (new Date()) - baseTime;
				var s = Math.floor(diff/1000);
				var m = Math.floor(s/60);
				var h = Math.floor(m/60);
				timerElement.innerHTML = [h.pad(), (m%60).pad(), (s%60).pad()].join(':');
				if( callbackFn && limit > 0 && diff >= limit ) { callbackFn(); }
				else if(allowRun) { t = setTimeout(function(){ run(limit, callbackFn); }, 500); }
			}
		};
		var start = function(limit, callbackFn){//For positive values of limit, after limit seconds, callbackFn() will be called.
			limit = (!limit) ? 0 : limit;
			callbackFn = (!callbackFn) ? null : callbackFn;
			allowRun = 1;
			run(limit*1000, callbackFn);
		};
		var stop = function(){
			allowRun = 0;
			run();//perform a last update just in case clock has rolled over to next whole second.
		};
		var reset = function(){
			stop();
			baseTime = new Date();
			if(timerElement) { timerElement.innerHTML = '00:00:00'; }
		};
		reset();
		this.reset = reset;
		this.start = start;
		this.stop = stop;
	};

You will see changes to functions start and run . (Maybe other changes too, as I tidied everything up after running jsLint).

Here's how to call timer.start :

var limit = 60;//seconds
  timer.start(limit, function() {
  	timer.stop();
	// ........
	// statement(s) which cause the game to terminate
	// and any other actions on game failure (eg. show the answer)
	// ........
  });

I'll let you work out where this code belongs. It shouldn't be too hard to work out.
Hint: It must run each time the user starts a new game.

In playing around, I found I wanted the limit to be variable and implemented a mechanism to select froma range of options. If you find the same, it's not difficult to implement.

Happy coding.

Airshow

Thanks again for your help..:)

I will work with your code...then I will post it here if I will finish it..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.