0

I want to loop through the buttons 30 times a second i have an array in which i have listed the buttons

function Btn_check(){
    for(var i in buttons){
        var buttons_name = [];
        buttons_name[i] = buttons[i].name+'_Btn';
        document.getElementById(buttons_name[i]).onclick = function() {
            //do something here
        }
    }
}

setInterval(Btn_check(), 1000/30);

in my HTML i just have a list of buttons like so

<a href="#" id="1_Btn" class="button">1</a>
<a href="#" id="2_Btn" class="button">2</a>
<a href="#" id="3_Btn" class="button">3</a>
//etc...

always when i click on a button it thinks i clicked the last button on the page

frankakn_7
  • 31
  • 1
  • 6
  • 4
    Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Heretic Monkey Aug 30 '16 at 17:46

1 Answers1

1

Not sure exactly what you are trying to do. It looks like you are looping through object properties of 'buttons' - which is unclear what buttons is supposed to be. And not sure why you need a button_names array when, if fetched properly, buttons should provide you with the node and its properties - assuming that buttons is all elements with classname buttons.

So here's my best effort at what you're trying to accomplish:

var buttons = document.querySelectorAll(".button");
function Btn_check(){
    for(var i=0; i<buttons.length; i++) {
      buttons[i].onclick = (function(n) {
        return function() {
          alert(buttons[n].getAttribute("id"));
        }
      })(i);

    }
}

setInterval(Btn_check(), 1000/30);

A fiddle: https://jsfiddle.net/bcyab7z4/

aek
  • 825
  • 1
  • 9
  • 17
  • that was actually not quite what i expected but it helped me out allot so thx :D – frankakn_7 Aug 30 '16 at 19:14
  • glad it helped. =) – aek Aug 30 '16 at 19:15
  • i still have a question, before i had the interval call the function in which there was the for loop and it actually worked, the only problem was that the code thought i had always pressed the last button in the loop so no matter which button i pressed it thought i always pressed the same button do you know why ? – frankakn_7 Aug 30 '16 at 19:35
  • I think this can explain it better than I can: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures – aek Aug 30 '16 at 20:28