setTimeout我无法再次启动该功能

时间:2017-10-05 06:25:10

标签: javascript settimeout

我是JavaScript的新手。在redPic.onclick中我想重置超时然后再次启动它。我不想使用jQuery。有可能吗?

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

2 个答案:

答案 0 :(得分:1)

是的,只需再次调用setTimeout:

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

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

答案 1 :(得分:0)

希望这会有所帮助:



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>
&#13;
&#13;
&#13;

修改

我添加了一个逻辑,不重复图像的相同位置。还添加了点更新功能。