using setTimeout synchronously in JavaScript

后端 未结 9 1706
无人及你
无人及你 2020-12-02 12:40

I have the following scenario:

setTimeout(\"alert(\'this alert is timedout and should be the first\');\", 5000);
alert(\"this should be the second one\");


        
相关标签:
9条回答
  • 2020-12-02 13:42

    Just put it inside the callback:

    setTimeout(function() {
        alert('this alert is timedout and should be the first');
        alert('this should be the second one');
    }, 5000);
    
    0 讨论(0)
  • 2020-12-02 13:42

    You could attempt to replace window.setTimeout with your own function, like so

    window.setTimeout = function(func, timeout) {
        func();
    }
    

    Which may or may not work properly at all. Besides this, your only option would be to change the original code (which you said you couldn't do)

    Bear in mind, changing native functions like this is not exactly a very optimal approach.

    0 讨论(0)
  • 2020-12-02 13:45
    setTimeout(function() {
      yourCode();    // alert('this alert is timedout and should be the first');
      otherCode();   // alert("this should be the second one");
    }, 5000);
    
    0 讨论(0)
提交回复
热议问题