简体   繁体   中英

Using a function to slowly increase the background colors' numbers

I'm trying to slowly increase the color of a background with this code:

<script type="text/javascript">
        let container = document.querySelector(".container")
        for(let i = 0 ; i<50; i++) {
            setTimeout(function() {
                container.style.background = `rgb(${i} , ${i}, ${i})`},
                1000);
            }
</script>

I'm not sure why it isn't working. It doesn't seem to iterate correctly when I console.log(i). I want it to pause for every iteration. How do I do this?

You can fix this issue by multiplying i with setTimeout delay like:

for (let i = 0; i < 50; i++) {
   setTimeout(function() {
      container.style.background = `rgb(${i} , ${i}, ${i})`
   }, 1000 * i);  // <----- like this
}

DEMO:

 let container = document.querySelector(".container") for (let i = 0; i < 255; i++) { setTimeout(function() { //var randomColor = Math.floor(Math.random() * 12777215).toString(16); container.style.background = `rgb(${i} , ${i}, ${i})` }, 1000 * i); }
 <div class="container" style="width:100px;height:100px"></div>

Demo (from black to white):

 let container = document.querySelector(".container") let container2 = document.querySelector(".container2") for (let i = 0; i < 256; i++) { setTimeout(function() { container.style.background = `rgb(${i} , ${i}, ${i})` container2.textContent = `rgb(${i} , ${i}, ${i})` }, 50 * i); }
 <div class="container" style="width:200px;height:100px"></div> <div class="container2" style="width:200px;height:100px"></div>

setTimeout is asynchrone

<script type="text/javascript">
    let container = document.querySelector(".container")
    let i = 0;
    function nextTimeout(){
      setTimeout(function() {
            container.style.background = `rgb(${i} , ${i}, ${i})`;
            i++;
            if(i<50){
              console.log('next');
              nextTimeout()
            }
          },
      1000);

    }
    nextTimeout();                 
</script>

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