zoukankan      html  css  js  c++  java
  • 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. 

  • 相关阅读:
    Maven
    Maven
    Maven
    Maven
    Maven
    Maven
    Maven
    Maven
    Maven教程
    SASS
  • 原文地址:https://www.cnblogs.com/chucklu/p/14305273.html
Copyright © 2011-2022 走看看