+-
在典型的ajax响应中,您只需将数据打印到div。我想获取数据响应并将其拆分为一个数组,然后迭代该数组并在追加之间添加随机延迟。
在此特定示例中,我将响应分为每个
标签。然后,我希望在打印这些响应之前添加一个延迟。
到目前为止,这对我没有用。即使我使用setTimeout遍历数组,它也只会完整显示数据响应。
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "/a_example.php?sim",
target: '#crap', // target element(s) to be updated with server response
//GET method is used
type: "POST",
//pass the data
data: data,
//Do not cache the page
cache: false,
success: function(data) {
var patt = /<p>(.*?)<\/p>/g;
var result = data.match(patt);
var i;
//alert(result.length);
for (i = 0; i < result.length; i++) {
showResultMock(result[i]);
}
},
complete: function() {
}
});
function showResultMock(result){
setTimeout(function(){ $('#modaldraftdetails .modal-body .draft-results').append(result); }, 2000);
}
0
投票
投票
您可以递归使用function
,然后使用Math.random()
添加如下所示的随机延迟:
let results = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
i = 0,
maxDelay = 2000;
function printVal(val) {
if (i < results.length) {
console.log(val);
setTimeout(() => {
i++; printVal(results[i]);
}, Math.random() * maxDelay)
}
}
printVal(results[i])
0
投票
投票
尝试使用递归而不是迭代。像这样的东西:
const $resultsContainer = $('#results')
const results = [1,2,3]
function showResults(results) {
if (!results.length) return
setTimeout(function(){
const result = results.shift()
$resultsContainer.append(`<p>${result}</p>`)
showResults(results)
}, 2000)
}
showResults(results)