javascript setInterval() 如何与 button.onclick 一起工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15606480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:23:48  来源:igfitidea点击:

How does setInterval() work with button.onclick

javascriptsetinterval

提问by Alex Silverman

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. But if I take the pageLoad function away, then startButton is null and I can't do anything with it.Thanks in advance, guys!

我希望仅在单击按钮时调用 alertMe 函数,但它会在页面加载时立即被调用(调用 setInterval 调用该函数)。但是,如果我取消 pageLoad 函数,那么 startButton 为空,我无法用它做任何事情。提前致谢,伙计们!

/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");
}

回答by ahren

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

    startButton.onclick = alertMe;
}

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

Move your interval inside the alertMefunction, and pass that as a reference to startButton.onclick

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

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

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

回答by Teneff

basically you need to do it like this:

基本上你需要这样做:

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

what it does is it sends reference to the alertMefunction

它的作用是发送对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 alertMefunction

这将发送对匿名函数的引用,该函数将调用该alertMe函数