Why `alert()` after `setTimeout()` is not called as expected?

前端 未结 1 2023
清酒与你
清酒与你 2021-01-29 09:25

Why alert() after setTimeout() is not called as expected?

function run() {
   setTimeout(\'\', 5000)
   alert(\'Welcome!\')
}

run()
         


        
1条回答
  •  离开以前
    2021-01-29 10:05

    setTimeout('', 5000) won't do anything. It won't delay the next line of code if that's what you're trying to do and by specifying an empty string for the first argument, you've not given it any code to run when the setTimeout() does actually fire so it does nothing.

    If you want the alert to fire in 5 seconds, then you do this:

    setTimeout(function() {
        alert("Welcome!");
    }, 5000);
    

    If you want the alert to pop up after the page has loaded, then you need to hook up to an event that signifies the page is loaded or just position your alert inside a

    0 讨论(0)
提交回复
热议问题