【问题标题】:Javascript check counter and repeat functionJavascript检查计数器和重复功能
【发布时间】:2015-11-17 10:47:05
【问题描述】:

我有一个 html 页面,我正在使用 JavaScript 创建一个函数,该函数显示 2 张图像(第一个在 5 秒和 10 秒之间,第二张在 10 秒和 20 秒之间)并每 30 秒重复一次。 我试过了

var cmp=0
function main() {
window.setTimeout(main,30000);
cmp+1;
if (cmp >= 5 and cmp < 10)
    show_image_1 ();
if (cmp >= 10 and cmp < 15)
    show_image_2 ();
}

但我不知道如何检查每一秒的时间。

【问题讨论】:

  • 添加完整代码。见minimal reproducible example
  • 如果你想每秒检查一次时间,你需要你的脚本每秒运行一次。另外,请注意 setTimeout() 需要以毫秒为单位的参数,而不是秒。
  • setInterval 会更适合你。

标签: javascript html counter


【解决方案1】:

定义一个Interval,然后根据它显示图像:

window.setInterval(updateImg, 1000);
var timer = 0;
var imageSrc = document.getElementById("imageSrc");
imageSrc.style.display = "none";

function updateImg() {
    timer += 1;
    if (timer > 30) {
        timer = 0;
    }
    if (timer >= 5 && timer <= 10) {
        imageSrc.style.display = "block";
        imageSrc.src = "http://lorempicsum.com/futurama/255/200/1";
    } else if (timer >= 10 && timer <= 20) {
        imageSrc.style.display = "block";
        imageSrc.src = "http://lorempicsum.com/futurama/255/200/2";
    } else {
        imageSrc.style.display = "none";
    }
}
&lt;img src="" id="imageSrc"&gt;

JsFiddle:http://jsfiddle.net/ghorg12110/z6vfn1nb/

【讨论】:

  • 它工作得很好,但是当 timer = 30 时我怎样才能让它停止
  • 删除if (timer &gt; 30) { timer = 0; }
【解决方案2】:

这是我的建议:

// Define the images and the duration of each one in seconds (a missing "src" means the image will be empty):
var steps=[
    {duration: 2},
    {duration: 3, src:'one.jpg'},
    {duration: 5, src:'two.jpg'},
    {duration: 5},
];

// Index of current step: Will cylce from 0 to steps.length:
var currentStep=0;

// Periodic function to show the current step, and re-invokes itself cyclically:
function nextStep()
{
    var step=steps[currentStep];
    var img=document.getElementById("myimg");
    if (step.src)
    {
        img.src=step.src;
        img.style.visibility="visible";
    }
    else
    {
        // When there is no "src" in the current step: Hide the image:
        img.style.visibility="hidden";
    }
    currentStep=(++currentStep % steps.length);
    setTimeout(nextStep, 1000*step.duration);
}

要开始循环,您必须致电nextStep()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多