繁体   English   中英

'when' 和 'setTimeout' function 无法正常工作

[英]'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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM