I want to execute a function that makes a call to ajax during intervals of 800 milliseconds and later after 10 seconds, to make stop of the setInterval (This in particular does not complicate me), the problem is that the call of this function depends on values values that you receive when you complete a promise, however, calling my function with the setInterval within the results of my promise does not work, the code I have done is the following:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Asincrono</title>
</head>
<body>
<h1>Prueba</h1>
<div style="margin-left: 50px;">
<p>Esperando....</p>
</div>
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script>
$(document).ready(function (){
var interval = null;
var condition = true;
var ruta= "saludo";
var promesa = funcionAsync(ruta);
promesa.then(function(datos){console.log(datos);
var a = datos['nombre'];
// Quiero que funcione, que se llame a esta función varias veces
interval = setInterval(funcionAsyncThree(datos['nombre']), 800);
// Espero que se llame a ajaxFn despues de 10seg una vez recibida la respuesta en la promesa.
setTimeout(ajaxFn(a), 10000);
})
function ajaxFn (a) {
console.log('Termine la totalidad del tiempo ir a: ',a);
clearInterval(interval);
}
console.log("Termine");
});
function funcionAsyncThree(nombre){
jQuery.ajax({
url: 'http://localhost:4567/' + nombre,
type: 'GET',
dataType: "json",
complete:function (response) {
var json = $.parseJSON(response.responseText);
console.log(json);
console.log(response);
}
});
}
function funcionAsync(token){
// La función devuelve una Promise
return new Promise(function(resolver, rechazar){
jQuery.ajax({
url: 'http://localhost:4567/' + token,
type: 'GET',
dataType: "json",
success : function(data){ resolver(data)},
error : function(error){rechazar(error)}
});
});
}
</script>
</body>
</html>
From the Chrome console, my function functionAsyncThree is only executed once, when I want it to run until the end of 10sec and the parameter 'a' send it after that time:
Any solution? As you can continue executing for a while the function callAsyncThree when it depends on values that a promise answers. Greetings!