Doraemon 24 Doraemon 24 - 3 months ago 10
Javascript Question

I want to update an output list every 1 second using setInterval(), but it gets infinity loop output

i want to update my list of name every 1 second so i try setinterval() but it gets loop. any solution?

<script>
getcus();
function getcus(){
$(document).ready(function() {
$.get('<?php echo base_url();?>index.php/site/get_all_customer_ajax', function (data) {
var obj = JSON.parse(data)
for (var i=0;i<obj.customer.length;++i)
{
$('#names').append(obj.customer[i].first_name + "<br>");
}
});
});
setInterval(getcus, 1000);
};




output

Maria

Jose

Clark

Maria

Jose

Clark

Maria

Jose

Clark

Maria

Jose

Clark


to infinity..

Answer

Empty the #name div before append to it setTimeout the getfocus function, because it call itself so you dont need setInterval in this case. use setTimeout in success callback to make sure next request will call after first request is success

Sorry about my english

$(document).ready(function() { 
	 getcus();
});

function getcus(){
	 $.get('<?php echo base_url();?>index.php/site/get_all_customer_ajax', function (data) {
		 var obj = JSON.parse(data);
		 $('#names').empty();
		 for (var i=0;i<obj.customer.length;++i)
		 {
		 	$('#names').append(obj.customer[i].first_name + "<br>");
		 }
          setTimeout(getcus, 1000);
	});
	
};