如何添加onclick事件以启动计时器

时间:2019-02-11 18:47:08

标签: javascript onclick mouseevent

编码新手。创建了一个计时器,当我按下“ gameStart”按钮而不是页面加载时,我想启动它。不知道在哪里插入我的“ onclick”。谢谢

<div id= "startButtons">
        <button  id= "gameStart">Get Going!</button>

<script>

var timeleft = 15;

var downloadTimer = setInterval(function function1(){
  document.getElementById("countdown").innerHTML = timeleft + 
"&nbsp"+"seconds remaining";

  timeleft -= 1;
  if(timeleft <= 0){
    clearInterval(downloadTimer);
    document.getElementById("countdown").innerHTML = "Time is up!"
  }
}, 1000);

    console.log(countdown);

</script>

3 个答案:

答案 0 :(得分:1)

您只需要在div中添加事件监听器click函数。

这里有一些工作代码:

document.getElementById("gameStart").addEventListener("click", function(){
    var timeleft = 15;

    var downloadTimer = setInterval(function function1(){
    document.getElementById("countdown").innerHTML = timeleft + 
    "&nbsp"+"seconds remaining";

    timeleft -= 1;
    if(timeleft <= 0){
        clearInterval(downloadTimer);
        document.getElementById("countdown").innerHTML = "Time is up!"
    }
    }, 1000);

    console.log(countdown);
});
        <div id= "startButtons">
          <button  id= "gameStart">Get Going!</button>
        </div>
        <div id= "countdown"></div>

答案 1 :(得分:0)

您将onclick事件放在按钮上,如下所示:

<div id= "startButtons">
    <button  id= "gameStart" onclick="">Get Going!</button>
</div>

然后,您必须修改功能以在单击之前不启动: var timeleft = 15;

// global variables for reference
var downloadTimer;
var downloadTimer;

function startInterval() {  // everything inside this function that is called with click on button
var downloadTimer = setInterval(function function1(){
      document.getElementById("countdown").innerHTML = timeleft + 
    "&nbsp"+"seconds remaining";

downloadTimer = setInterval(function function1(){
  document.getElementById("countdown").innerHTML = timeleft + 
"&nbsp"+"seconds remaining";

  timeleft -= 1;
  if(timeleft <= 0){
    clearInterval(downloadT

imer);
        document.getElementById("countdown").innerHTML = "Time is up!"
      }
    }, 1000);
}

答案 2 :(得分:0)

您需要点击按钮,对代码进行简单的修改将帮助您实现所需的目标。

@Query("SELECT * FROM exercises WHERE muscle_group LIKE :muscle")
    LiveData<List<Exercise>> getByMuscle(List<Integer> muscle);