nudelkopf nudelkopf - 2 years ago 78
Javascript Question

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:

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();"GET", "servo.php?dir=P1-11=" + tilt, true);

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>

Answer Source

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

setInterval(tilt, 5000); 

Will call tilt() every 5 seconds...


Added clearInterval example:

var doIt = setInterval(tilt, 5000);

You can then clear / stop it like so:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download