setInterval()如何与button.onclick一起使用

Ale*_*man 2 javascript setinterval

我希望只有在单击按钮时才会调用alertMe函数,但是它会被调用(调用setInterval调用它),就像页面加载一样.但是,如果我取走pageLoad函数,那么startButton为null,我无法用它做任何事情.谢谢你,伙计们!

/when user clicks start, start the animation
window.onload = pageLoad;

function pageLoad() {
    var startButton = document.getElementById("start");

    startButton.onclick = setInterval(alertMe,200);
}

function alertMe() {
  alert("hi");
}
Run Code Online (Sandbox Code Playgroud)

ahr*_*ren 7

function pageLoad() {
    var startButton = document.getElementById("start");

    startButton.onclick = alertMe;
}

function alertMe() {
  setInterval(function(){
    alert("hi");
  },200);
}
Run Code Online (Sandbox Code Playgroud)

alertMe函数内移动您的间隔,并将其作为参考传递给startButton.onclick

演示:http://jsfiddle.net/gHS4a/

  • @AlexSilverman请记住,单击多个按钮将导致单独的计时器累积。 (2认同)