Svetlozar
Svetlozar

Reputation: 987

setTimeout I can't start the function again

I'm new with JavaScript. In redPic.onclick I want to reset timeout and then start it again. I don't want to use jQuery. Is it possible?

let redPic = document.createElement('img');
redPic.src = "610f326c4fa418d6221909abdb8c67a824837df3f7397b840d9a3376.png";
redPic.width = "90";

function putPicOnRandomPlace() {
  let showRedPic = document.getElementById(Math.floor(Math.random() * 9) + 1);
  showRedPic.appendChild(redPic);
}

putPicOnRandomPlace();
let timeOut = setTimeout(function() {
  alert('game over!');

}, 3000)

redPic.onclick = function() {
  putPicOnRandomPlace();

  clearTimeout(timeOut);

  timeOut = setTimeout(function() {
    alert('game over!');

  }, 3000)
}

Upvotes: 0

Views: 83

Answers (2)

xGeo
xGeo

Reputation: 2139

Hope this helps:

let redPic = document.createElement('img');
redPic.src = "https://yt3.ggpht.com/-VU845Dzzu-w/AAAAAAAAAAI/AAAAAAAAAAA/55Lhvq94LfI/s900-c-k-no-mo-rj-c0xffffff/photo.jpg";
redPic.width = 60;
redPic.height = 60

let gameover = function() { alert(`Game Over!`); updatePoints(0); points = 0; }
let prevNum;
function putPicOnRandomPlace() {
  let showRedPic = document.getElementById(randomNumber());
  showRedPic.appendChild(redPic);
}

function updatePoints(pts) {
   document.getElementById('pts').innerHTML = pts;
}
let points = 0;
randomNumber = function() {
   let newNum = Math.floor(Math.random() * 9) + 1;
   if(newNum !== prevNum) {
      prevNum = newNum;
      return newNum;
   }
   else
      return randomNumber();
}

putPicOnRandomPlace();
let timeOut = setTimeout(gameover, 3000);

redPic.onclick = function() {
  points++;
  updatePoints(points);
  putPicOnRandomPlace();

  clearTimeout(timeOut);

  timeOut = setTimeout(gameover, 3000)
}
.board {
  float: left;
  border: 5px solid black;
  max-width: 180px;
  clear: both;
}

.tile {
  width: 58px;
  height: 58px;
  float: left;
  background-color: grey;
  margin: 0;
  border: 1px solid white
}
<div class="board">
  <div id="1" class="tile"></div>
  <div id="2" class="tile"></div>
  <div id="3" class="tile"></div>
  <div id="4" class="tile"></div>
  <div id="5" class="tile"></div>
  <div id="6" class="tile"></div>
  <div id="7" class="tile"></div>
  <div id="8" class="tile"></div>
  <div id="9" class="tile"></div>
</div>
<div style="clear: both;">Points: <span id="pts">0</span></div>

EDIT:

I added a logic to not repeat the same position for the image. Also added a points update functionality.

Upvotes: 0

Thayne
Thayne

Reputation: 7002

Yes, just call setTimeout again:

let endGame = function() { alert('game over!'); };
let timeOut = setTimeout(endGame, 3000);

redPic.onclick = function() {
  putPicOnRandomPlace();
  clearTimeout(timeOut);
  timeOut = setTimeout(endGame, 3000);
};

Upvotes: 1

Related Questions