简体   繁体   中英

How can I write a function that takes X amount of seconds?

I want to write a javascript function that takes very close to 5 seconds to run. How can I make that guarantee?

I have tried

  function wait(numSeconds) {
    var end = new Date().getMilliseconds() + numSeconds * 1000;
    while (new Date().getMilliseconds() <= end) {}
  }

but this just crashes the page.

You cannot freeze the page without freezing the page.

You're trying to write a function that runs for 5 seconds straight.
Javascript runs on the UI thread, so the page will be frozen whenever any code runs.

In short, you can't do that.
You need to write asynchronous code , probably by using setTimeout() .

您可以使用:

var t = setTimeout(function(){alert('done')},5000);

If you want to wait 5 seconds before doing something, use setTimeout or setInterval . Otherwise, just eating up user time is a bad idea. In fact, the browsers will interrupt your script if it takes too long to do something, which your function most certainly will do.

(Ignoring for the moment why you shouldn't really do this...)

The reason your code is freezing the browser is that your while condition will never become true (for numSeconds of 1 or more).

The .getMilliseconds() method returns just the milliseconds part of the date, ie, a number between 0 and 999. For numSeconds of 1 of more your end will always be greater than 999.

Try using .getTime() instead of .getMilliseconds() . Or if you don't care about supporting old browsers uses Date.now() .

You could just use javascripts setTimeout instead of your own wait function.

setTimeout excecutes a function after a certain amount of time.

For example:

setTimeout(function(){}, 5000);

Would just wait 5 seconds.

See more at w3schools .

Strictly speaking, what you ask cannot be done because, as you've seen, the page will freeze while you wait.

As a practical matter, though, I suspect that what you really want is the something like this:

function waitawhile() {
    setTimeout( function() {
        alert('5 seconds has passed');
    }, 5000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM