简体   繁体   中英

Div Opacity Change with setTimeout function not working

I am trying to change the opacity of a div for a given interval so that the object consistently pulses. The element will continually pulse until a button is pressed. The code below doesn't get the element to continually change opacity and I don't know why.

function setRandomZoneOpacity(){
    while(buttonpressed==false;){
        var n=randomIntFromInterval(0,1);
        var zone_string = zones[n];
        document.getElementById(zone_string).style.filter="opacity(100%)";
        setTimeout(function(){};,1000);
        document.getElementById(zone_string).style.filter="opacity(0%)";
        setTimeout(function(){};,1000);
    }
};
function randomIntFromInterval(min,max){ //random number generator
    return Math.floor(Math.random()*(max-min+1)+min);
}

setTimeout 不正确

setTimeout(function(){ //your code here }, 1000);

setTimeout(callback, delay) does NOT halt script execution for delay milli-seconds. What it does is queue the callback function to be executed after delay ms.

You should either do it like this:

setTimeout(function(){
    document.getElementById(zone_string).style.filter="opacity(100%)";
}, 1000);
setTimeout(function(){
    document.getElementById(zone_string).style.filter="opacity(0%)";
}, 2000);

... or this:

setTimeout(function(){
    document.getElementById(zone_string).style.filter="opacity(100%)";
    setTimeout(function(){
        document.getElementById(zone_string).style.filter="opacity(0%)";
    }, 1000);
}, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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