Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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");
}
like image 200
Alex Silverman Avatar asked Sep 17 '26 05:09

Alex Silverman


2 Answers

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/

like image 173
ahren Avatar answered Sep 19 '26 18:09

ahren


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

like image 21
Teneff Avatar answered Sep 19 '26 18:09

Teneff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!