Search code examples
javascripttimeoutdo-whiletogglebutton

Do function with timeout while togglebutton is pressed


I want to run a function with a timeout of 2000 ms. The function should just run while toggleButton is pressed.

When I run this function my CPU explodes:

do {
  setTimeout(function () {
    me.pushMockData();
  }, 2000);
}
while (liveButton.getPressed() != false);

Solution

  • Your CPU explode because you create Timeout again, again and again really fast in your loop when button is pressed. If you want to run your function every 2 second :

    • You should test if the the button is pressed.
    • Use setInterval
    • Inside setInterval, check if the button is still pressed, if not, clearInterval

    https://www.w3schools.com/jsref/met_win_setinterval.asp

    If you just want to active your function 2 second later, use setTimeout inside if.