最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How does setInterval() work with button.onclick - Stack Overflow

programmeradmin2浏览0评论

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!

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

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!

/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");
}
Share Improve this question asked Mar 25, 2013 at 1:54 Alex SilvermanAlex Silverman 2031 gold badge6 silver badges20 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11
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

DEMO: 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

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

发布评论

评论列表(0)

  1. 暂无评论