Based on the following method: http://www.ajaxblender.com/article-sources/jquery/call-settimeout-inside-of-object/index.html
My ajax call only fires once.
<body>
<div id="match-data"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
jQuery(function($){
function obj(){
var duration = 1000;
var tmpFnc = function(){ exec(); };
setTimeout(tmpFnc, duration);
function exec(){
$.ajax({
url: "web_service.php",
data: {
format: 'json'
},
success: function(data){
var resultHTML = "";
var json = $.parseJSON(data);
$.each(json, function(key, val){
var $team = json[key].name;
var $badge = json[key].crestUrl;
var $alt_text = json[key].shortName;
resultHTML += "<p>"+$team;
resultHTML += '<img style="width:100px;height:100px;" src="'+$badge+ '" alt="'+$alt_text+'"/></p>';
// console.log(resultHTML);
});
$("#match-data").append(resultHTML);
}
});
}
};
obj = new obj();
});
</script>
</body>
where I'm expecting it to repeat every second?
I think you're looking for setInterval:
setInterval(exec, duration);
That will call exec
every 1 second, when duration
is 1000
.
However, since you're doing an ajax call, it might be better to wait for the server to respond first before you wait a second:
success: function(data) {
// omitted
setTimeout(exec, duration);
}
Note: Your tmpFnc
function is unnecessary.
basicly change your code like below
setInterval(tmpFnc, duration);
....
obj(); //not obj = new obj();