在JavaScript中,什么相当于Java的Thread.sleep() ?


当前回答

这最终帮助了我:

    var x = 0;
    var buttonText = 'LOADING';

    $('#startbutton').click(function(){
        $(this).text(buttonText);
        window.setTimeout(addDotToButton,2000);
    })

    function addDotToButton(){
        x++;
        buttonText += '.';
        $('#startbutton').text(buttonText);

        if (x < 4) window.setTimeout(addDotToButton, 2000);
        else location.reload(true);
    }

其他回答

假设你能够使用ECMAScript 2017,你可以通过使用async/await和setTimeout来模拟类似的行为。下面是一个睡眠函数的例子:

async function sleep(msec) {
    return new Promise(resolve => setTimeout(resolve, msec));
}

然后你可以在任何其他异步函数中使用sleep函数,就像这样:

async function testSleep() {
    console.log("Waiting for 1 second...");
    await sleep(1000);
    console.log("Waiting done."); // Called 1 second after the first console.log
}

这很好,因为它避免了需要回调。缺点是它只能在异步函数中使用。在后台,testSleep函数被暂停,在睡眠完成后,它将被恢复。

中数:

await表达式导致异步函数的执行暂停,直到 Promise被满足或拒绝,并恢复异步的执行 实现后的功能。

完整的解释见:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

setTimeout不会在你自己的线程上保持和恢复。睡眠。在Javascript中没有真正的对等

这最终帮助了我:

    var x = 0;
    var buttonText = 'LOADING';

    $('#startbutton').click(function(){
        $(this).text(buttonText);
        window.setTimeout(addDotToButton,2000);
    })

    function addDotToButton(){
        x++;
        buttonText += '.';
        $('#startbutton').text(buttonText);

        if (x < 4) window.setTimeout(addDotToButton, 2000);
        else location.reload(true);
    }

试试这段代码。我希望这对你有用。

function sleep(seconds) 
{
  var e = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= e) {}
}

或者您可以使用setInterval函数,在指定的毫秒数之后调用特定的函数。只需为setInterval原型执行谷歌即可。我不太记得了。