简体   繁体   English

在JavaScript中暂停一会儿

[英]Pausing for a split moment in JavaScript

I have the following JavaScript code: 我有以下JavaScript代码:

var cILo=true;

var img1="images/title-2a.png";
var img2="images/title-2b.png";

function loadblinker() {
    for (var i=0,l=Math.floor(Math.random()*10);i<l;++i) {
        cILo=!cILo;
        if (cILo) {
            document.getElementById("lamp").src=img1;
        } else {
            document.getElementById("lamp").src=img2;
        }
        !!!! THIS LINE HERE !!!!
    }
    document.getElementById("lamp").src=img1;
    setTimeout("loadblinker()",Math.floor(Math.random()*10000));
}

Where I have marked the code with the phrase "!!!! THIS LINE HERE !!!!" 我在代码上标记了短语“ !!!!这条线!!!!”的地方 , I need some way to pause the execution for a split second. ,我需要一些方法来暂停执行一秒钟。 This code, when it is done, is going to give the appearance of a short circuiting light (light in the video games). 完成后,此代码将产生短路光(视频游戏中的光)的外观。 I was wondering as to how I would pause the code seeing as there appears to be no natural method. 我想知道我应该如何暂停代码,因为似乎没有自然的方法。

I think a better approach would be to eliminate the for loop by using setInterval . 我认为更好的方法是通过使用setInterval消除for循环。 You could then clear the interval after Math.floor(Math.random()*10) iterations. 然后,您可以清除Math.floor(Math.random()*10)迭代之后的时间间隔。 I wouldn't recommend blocking execution by just spinning in a loop. 我不建议仅通过循环旋转来阻止执行。 Most browsers freak out when you do that. 大多数浏览器在执行此操作时都会感到恐惧。

Typically this is handled in JavaScript by calling setTimeout, passing it the code to be executed after the delay. 通常,这是通过在JavaScript中调用setTimeout并在延迟后将要执行的代码传递给它来处理的。 Or in other words, instead of pausing within a function, you break your function in two: one part to be executed before the delay and the next part to be executed after. 换句话说,不是在函数中暂停,而是将函数分为两部分:一部分要在延迟之前执行,而另一部分要在延迟之后执行。

You are already recursively calling your function via setTimeout, so you are almost there. 您已经通过setTimeout递归调用了函数,因此您已经差不多了。 See if you can restructure your code so that you get rid of the for loop and instead pass in the maximum number of iterations. 查看是否可以重组代码,以便摆脱for循环,而传递最大的迭代次数。 Decrement that counter on each call. 在每次通话时减少该计数器。 If after the decrement, your counter is greater than zero, call setTimeout to call the function again. 如果递减后您的计数器大于零,请调用setTimeout再次调用该函数。

function pause(ms) 
{
    var d = new Date();
    var c = null;

    do
    {
        c= new Date();
    } 
    while(c - d < ms);
}

Use pause(1000); 使用pause(1000); to pause for 1 second. 暂停一秒钟

Courtesy of this website . 本网站提供

Javascript in browsers does not have the ability to do a synchronous pause. 浏览器中的Javascript无法执行同步暂停。 You can hack your way around it, as muntoo suggested, but you shouldn't do it. 您可以按照muntoo的建议修改自己的方式,但是不应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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