There is a script:

function func(){ console.log('start'); ... } func(); console.log('end'); 

What code to write instead of ... so that between the first log and the exit from the function (and not between the first and second logs) 1 second is passed?

If you do this, then the time log will be displayed a second after the end log:

 function func(){ console.log('start'); setTimeout(function(){console.log('time');}, 1000); } func(); console.log('end'); 
  • one
    What you want to do is totally discouraged by javascript. It is better to give up this and learn the asynchronism, or at least use this same setTimeout - andreymal
  • @andreymal, I understand, maybe I will do it without it, but still, if somehow you can, you better know ... - Max Nest
  • one
    You want the bad, so in the name of the common good consider that in any way - andreymal

1 answer 1

This is from the category of "bad advice": you can create a wait function that simply clogs the JS.

 function wait(ms) { let current_date = +new Date(); while (current_date + ms > +new Date()) {} } function func() { console.log('start'); wait(1000); // 1000ms = 1s } func(); console.log('end'); 

(Snippet displays the result after the end of the JS)

I hope you understand that JS is single-threaded. Creating such a situation, you probably break the concept of language. This should not happen, you should not "freeze" the call stack.

And the setTimeout function refers to such a concept as "Web Api". This feature allows you to postpone the transmitted instructions for a specified time. As soon as this time passes, Web Api "throws" the transmitted instructions into the queue, called "call stack"

  • That is why I asked this question. :-) - Max Nest
  • do you feel warm in the room?) - Denis Stepanov