Javascript检查计数器和重复功能

时间:2015-11-17 10:47:06

标签: javascript html counter

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

{{1}}

但我没有找到如何每秒检查一次的时间。

3 个答案:

答案 0 :(得分:1)

定义间隔,然后根据以下内容显示图像:

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";
    }
}
<img src="" id="imageSrc">

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

答案 1 :(得分:0)

以下是我的建议:

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

答案 2 :(得分:-1)

你好!

我有一个有效的例子:http://jsfiddle.net/xwh9kfLm/

以下是代码,为了完整性:

<pre id="pre"></pre>
<img id="img" src="" alt="No image displayed.">

<script>
var pre = document.getElementById("pre"),
    img = document.getElementById("img"),
    src1 = "https://static.pexels.com/photos/17502/pexels-photo-medium.jpg",
    src2 = "https://static.pexels.com/photos/17505/pexels-photo-medium.jpg";
setInterval(function () {
    var seconds = (new Date()).getSeconds(),
        counter = seconds % 30; // Runs from 0 to 29
    pre.innerHTML = String(counter);
    if (counter === 5) {
        img.src = src1;
    } else if (counter === 10) {
        img.src = src2;
    } else if (counter ===  20) {
        img.src = "";
    }
}, 1000);

</script>

希望这会有所帮助。