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

偶尔善良 提交于 2019-12-11 21:02:42

问题


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.


回答1:


you can use:

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



回答2:


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().




回答3:


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.




回答4:


(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, i.e., 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().




回答5:


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.




回答6:


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);
}


来源:https://stackoverflow.com/questions/16823933/how-can-i-write-a-function-that-takes-x-amount-of-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!