Js: setTimeOut without function argument?

Js: setTimeOut without function argument?

Why do we need to pass a function to Javascript setTimeOut https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setTimeout

Why cannot we do sg simple like

setTimeOut(1000);

Can I pass an empty or nonexistant function in there?

I want to simply wait in a for loop after each iteration.

 

回答1

Javascript is single threaded. You can use setTimemout to postpone an operation, but the thread will continue. So

function some() {
  doStuff();
  setTimeout(otherStuff, 1000);
  doMoreStuff();
}

will run doStuff and doMoreStuff subsequently, and will run otherStuff after a second. That's why it's useless and impossible to use setTimeout as a delay per se.

If doMoreStuff should be postponed, you should make that the callback for the delay:

function some() {
  doStuff();
  setTimeout(doMoreStuff, 1000);
}

or both otherstuff and doMoreStuff delayed:

function some() {
  doStuff();
  setTimeout(function () {
               otherStuff();
               doMoreStuff()
             }, 1000);
}

Maybe my answer to this SO-question is usefull too. 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章