Search code examples
javascriptwhile-loopsettimeoutgreasemonkey

Javascript while setTimeout


I want to make a GreaseMonkey script. I want to have a setTimeout at the end of my while, but I don't know how to do that.

run();
function run(){
  var klovas = document.getElementById("light").innerHTML;
  var btn = document.getElementsByClassName("farm_icon farm_icon_a");
  if(klovas < 6){
    alert("Kevés egység van");
  } else {
    var i = 0;
    while (i < btn.length){
      if(typeof btn[i] != "undefined"){
        btn[i].click();
      }
    i++;
    setTimeout("run()", 3000);
    }
  }
}

With this code, the problem is that the setTimeout is not working and doesn't wait 3 seconds like it is supposed to.

I tried other ways, but nothing has worked.

EDIT

function run(){
  var klovas = document.getElementById("light").innerHTML;
  var btn = document.getElementsByClassName("farm_icon farm_icon_a");
  if(klovas < 2){
    alert("Kevés egység van");
  } else {
    var i = 0;
    while (i < btn.length){
      if(typeof btn[i] != "undefined"){
        btn[i].click();
      }
    i++;    
    }
  }
}
setInterval(run, 6000); 

I tryed this. Its runing every 6 sec, but i get error in website, that i cand click more than 5 times in a sec. So waiting 6secound when i open the page, and after click, and i get error. Its not jet working. :(


Solution

  • If you wanted it to only trigger once:

    function run(){
        var data = [1,2,3];
        var i = 0;
        while (i < data.length) {
            console.log(data[i]);
            i++;
        }
    }
    
    setTimeout(run, 3000);

    The way you wrote it now, it would repeat every 3 seconds.

    function run(){
        var data = [1,2,3];
        var i = 0;
        while (i < data.length) {
            console.log(data[i]);
            i++;
        }
        setTimeout(run, 3000);
    }
    
    run();

    But setInterval would accomplish the same results.

    function run(){
        var data = [1,2,3];
        var i = 0;
        while (i < data.length) {
            console.log(data[i]);
            i++;
        }
    }
    
    setInterval(run, 3000);

    EDIT

    User wanted to see what would happen if you call setInterval from inside the callback function. Note that the number of intervals grows exponentially every 3 seconds.

    setInterval causes the function to run every 3 seconds, while setTimeout causes the function to run once in 3 seconds.

    var numberOfIntervals = 0;
    
    function run(){
        setInterval(run, 3000);
        numberOfIntervals++;
        console.log(numberOfIntervals);
    }
    
    run();