Skip to content
Advertisement

How to execute code continuously in javascript?

I have a HTML-file and a PHP-file. The index.php displays a value which gets transferred to the servo.php. The servo.php writes the value in a file called /dev/servoblaster.

Currently the value only gets displayed if i click the button with my function. I would like that the value is displayed and sent continuously and not by the press of a button.

The two files can you find here: servo.php index.html

The function: (You will find it also in the HTML-file)

    function tilt() { var tilt = document.getElementById("tiltRange").value;
                      document.getElementById("tilt_Range").innerHTML = tilt;
                      var xhttp = new XMLHttpRequest();
                      xhttp.open("GET", "servo.php?dir=P1-11=" + tilt, true);
                      xhttp.send();
                    }

The body tag of the HTML-file:

    <button onclick="tilt()">Tilt</button>

    <input type="range" id="tiltRange" value="140" max="170" min="60">

    <text id="tilt_Range"></text>

Advertisement

Answer

You could use setInterval to call your script every n seconds:

setInterval(tilt, 5000); 

Will call tilt() every 5 seconds…

EDIT:

Added clearInterval example:

var doIt = setInterval(tilt, 5000);

You can then clear / stop it like so:

clearInterval(doIt) 

So you should assign a click handler to your “stop” button, that calls the clearInterval.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement