Javascript 睡眠/延迟/等待功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19389200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:24:03  来源:igfitidea点击:

Javascript sleep/delay/wait function

javascriptfunctiondelaysleepwait

提问by user2704237

Sorry if this question has already been asked here before, I could not find a suitable answer.

对不起,如果这个问题之前已经在这里问过,我找不到合适的答案。

I am wanting to create a JavaScript sleep/delay/wait function that I can call anywhere in the script, like jQuery's .delay()

我想创建一个 JavaScript 睡眠/延迟/等待函数,我可以在脚本中的任何地方调用它,比如 jQuery .delay()

I am not able to use setTimeout, as I have a script that is generated by php, and so am not able to put it into two different functions, with the timeout in the middle. I need to create a function that allows me to do

我无法使用 setTimeout,因为我有一个由 php 生成的脚本,因此无法将其放入两个不同的函数中,超时在中间。我需要创建一个允许我做的功能

alert("time started");
sleep(4000);
alert("time up");

I reallydo not want to use jQuery.

真的不想使用jQuery。

采纳答案by Deep

You cannot just put in a function to pause Javascript unfortunately.

不幸的是,您不能仅仅放入一个函数来暂停 Javascript。

You have to use setTimeout()

你必须使用 setTimeout()

Example:

例子:

function startTimer () {
    timer.start();
    setTimeout(stopTimer,5000);
}

function stopTimer () {
    timer.stop();
}

EDIT:

编辑:

For your user generated countdown, it is just as simple.

对于您的用户生成的倒计时,它同样简单。

HTML:

HTML:

<input type="number" id="delay" min="1" max="5">

JS:

JS:

var delayInSeconds = parseInt(delay.value);
var delayInMilliseconds = delayInSeconds*1000;

function startTimer () {
    timer.start();
    setTimeout(stopTimer,delayInMilliseconds);
}

function stopTimer () {
    timer.stop;
}

Now you simply need to add a trigger for startTimer(), such as onchange.

现在您只需添加一个触发器startTimer(),例如onchange

回答by Paul S.

You will have to use a setTimeoutso I see your issue as

你将不得不使用setTimeout所以我认为你的问题是

I have a script that is generated by PHP, and so am not able to put it into two different functions

我有一个由 PHP 生成的脚本,因此无法将其放入两个不同的函数中

What prevents you from generating two functions in your script?

是什么阻止您在脚本中生成两个函数?

function fizz() {
    var a;
    a = 'buzz';
    // sleep x desired
    a = 'complete';
}

Could be rewritten as

可以改写为

function foo() {
    var a; // variable raised so shared across functions below
    function bar() { // consider this to be start of fizz
        a = 'buzz';
        setTimeout(baz, x); // start wait
    } // code split here for timeout break
    function baz() { // after wait
        a = 'complete';
    } // end of fizz
    bar(); // start it
}

You'll notice that ainside bazstarts as buzzwhen it is invoked and at the end of invocation, ainside foowill be "complete".

您会注意到ainside在调用时baz开始,buzz在调用结束时,ainsidefoo将是"complete"

Basically, wrap everything in a function, move all variables up into that wrapping function such that the contained functions inherit them. Then, every time you encounter wait NUMBER secondsyou echoa setTimeout, end the functionand start a new functionto pick up where you left off.

基本上,将所有内容包装在一个函数中,将所有变量向上移动到该包装函数中,以便包含的函数继承它们。然后,每次你遇到时wait NUMBER secondsecho一个setTimeout,结束该功能,并开始了新的功能,拿起你离开的地方。

回答by Anil Agrawal

Here's a solution using the new async/await syntax.

这是使用新的 async/await 语法的解决方案。

async function testWait() {
    alert('going to wait for 5 second');
    await wait(5000);
    alert('finally wait is over');
}

function wait(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time);
    });
}

Note:You can call function wait only in async functions

注意:只能在异步函数中调用函数等待

回答by kamituel

The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.

与您指定的行为完全一致的行为在当前浏览器中实现的 JS 中是不可能的。对不起。

Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)

好吧,理论上您可以使用循环创建一个函数,其中循环的结束条件将基于时间,但这会占用您的 CPU,使浏览器无响应,并且设计非常糟糕。我什至拒绝为此写一个例子;)



Update:My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is notimplemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.

更新:我的回答得到了-1'd(不公平),但我想我会提到,在ES6(这是不是在浏览器中实现呢,也不是在默认情况下启用的Node.js),将有可能写以同步方式编写异步代码。为此,您需要承诺和生成器。

You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog postfor example (last example there).

您今天可以使用它,例如在带有和声标志的 Node.js 中,使用 Q.spawn(),例如参见这篇博客文章(最后一个例子)。

回答by Tushar

You can use this -

你可以用这个——

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

回答by Emi

You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.

您可以使用以下代码,它会递归调用函数以正确等待所需的时间。

function exportar(page,miliseconds,totalpages)
{
    if (page <= totalpages)
    {
        nextpage = page + 1;
        console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
        fnExcelReport(page);
        setTimeout(function(){
            exportar(nextpage,miliseconds,totalpages);
        },miliseconds);
    };
}