简体   繁体   English

我如何在此代码上插入setTimeout和setInterval

[英]How can i insert setTimeout and setInterval on this code

Is it possible to insert setTimeout and setInterval on this code? 是否可以在此代码上插入setTimeout和setInterval? I'm trying to make the background color change fro red to blue and will stop in three seconds. 我正在尝试使背景颜色从红色变为蓝色,并会在三秒钟后停止。 Thanks in advance for your help! 在此先感谢您的帮助!

<Script>

var flag = true;

function changeColor () {

    if(flag==true) {
        document.getElementById("yourId").style.background="red";
        flag=false;
    }

    else if (flag==false) {
        document.getElementById("yourId").style.background="#235CDB";
        flag = true;
    }
}


setInterval(

function changeColor () {

    if(flag==true) {
        document.getElementById("yourId").style.background="red";
        flag=false;
    }
    else if (flag==false){
        document.getElementById("yourId").style.background="#235CDB";
        flag = true;
    }
}, 400);// -->

</SCRIPT>

With setTimeout function, 使用setTimeout函数,

var flag = true;
for (var time = 400; time<=3000; time+=400){
    (function(time){
        setTimeout(changeColor,time);
    })(time);
}

function changeColor () {

    if(flag==true) {
        document.getElementById("yourId").style.background="red";
        flag=false;
    }
    else if (flag==false){
        document.getElementById("yourId").style.background="#235CDB";
        flag = true;
    }
}

with setInterval function, 使用setInterval函数,

You can keep another variable to keep a track of tatal time, and clear the interval when total time exceeds 3000 milliseconds.. 您可以保留另一个变量来跟踪总时间,并在总时间超过3000毫秒时清除间隔。

var flag = true;
var time = 0;

var interval = setInterval(changeColor,400);

function changeColor () {

    if(flag==true) {
        document.getElementById("yourId").style.background="red";
        flag=false;
    }
    else if (flag==false){
        document.getElementById("yourId").style.background="#235CDB";
        flag = true;
    }
    time += 400;
    if (time >= 3000){
       clearInterval(interval);
    }
}

Note: either of these won't stop after exactly 3 seconds because 3000 cannot be divided by 400. 注意:由于无法将3000除以400,因此其中任何一种都不会在3秒后停止。

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

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