简体   繁体   English

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

[英]How does setInterval() work with button.onclick

I want the alertMe function to be called only when the button is clicked, but it gets called (the setInterval gets called which calls that) AS SOON AS THE PAGE LOADS. 我希望只有在单击按钮时才会调用alertMe函数,但是它会被调用(调用setInterval调用它),就像页面加载一样。 But if I take the pageLoad function away, then startButton is null and I can't do anything with it.Thanks in advance, guys! 但是,如果我取走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");
}
function pageLoad() {
    var startButton = document.getElementById("start");

    startButton.onclick = alertMe;
}

function alertMe() {
  setInterval(function(){
    alert("hi");
  },200);
}

Move your interval inside the alertMe function, and pass that as a reference to startButton.onclick alertMe函数中移动您的间隔,并将其作为startButton.onclick的引用传递

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

basically you need to do it like this: 基本上你需要这样做:

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

what it does is it sends reference to the alertMe function 它的作用是发送对alertMe函数的引用

another way would be: 另一种方式是:

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

which would send a reference to an anonymous function which will call the alertMe function 它将发送一个匿名函数的引用,该函数将调用alertMe函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM