[英]'when' and 'setTimeout' function not working properly
我試圖通過延遲執行來即興創作一段代碼。
$(document).ready(
function testFunc(){
setTimeout(function(){console.log("something happening...")},1000)
}
$.when(testFunc()).done(function(){
//this code executes immediately, shouldn't it be executed after 1 sec or 1000 milliseconds
$('#tWrapper').removeClass("d-none");
$('#spinnerrr').remove();
});
});
So I want to do something (in my case to remove some class or HTML elements) after one function is finished (which will be an ajax call, but for now I am improvising the AJAX call with a code delay) but with the $. when() function 內部函數立即執行。
testFunc
必須是返回 promise 的 promise 或 function
const testFunc = new Promise(resolve => { { console.log("something waiting to happen...") setTimeout(function () { console.log("something happening...") resolve(); }, 1000); } }) $.when(testFunc).done(function () { console.log("something happened...") });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
做你想做的最好的方法就是在你的超時結束時執行 function,除非你的超時是異步的(這應該是你等待的)。
function setData(data) {
console.log("My article is called " + data.title);
console.log("And this is what I wrote: " + data.content);
}
function loadData() {
setTimeout(function () {
console.log("Data loaded.");
setData({ title: 'My first artile', content: '...' });
}, 1000);
}
此處的解決方案由 Stackoverflow 中的以下答案提供: stackoverflow.com/a/39914235/2181514
$(document).ready(function() {
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function something(){
$('#example').DataTable();
await sleep(500);
$('#spinnerrr').remove();
$('#tWrapper').removeClass("d-none");
}
something();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.