-1

I am trying to improvise a piece of code by delaying an execution.

$(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 the inside functions execute immediately.

jAdex
  • 332
  • 2
  • 11

2 Answers2

2

testFunc needs to be a promise or a function that returns a promise

            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>
McKabue
  • 1,733
  • 1
  • 15
  • 28
0

Best way to do what you want to do is just execute the function at the end of your timeout, unless something in your timeout is async (which then should be what you wait for!).

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);
}
TemporaryName
  • 437
  • 5
  • 15