简体   繁体   中英

count how many times function was executed

I've website with image on background and i'm willing to make it move from right to left and i do not want to use jQuery so here is my code which makes it do that movement

HTML Code

<div id="clouds_image"></div>

Javascript Code

var g = 0;
var speed=80;
var counter = 5;
function rollClouds() 
{
    document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
    g--;
    if (counter < 1) 
        clearInterval(interval);
}

interval = setInterval( function(){ rollClouds() }, speed)

This supposed to make the image moves from right to left and repeat its movement 5 times and counting down from 5 to 0 then will counter < 1 so it will execute clearInterval(interval) to stop it.

but i do not know why it keep repeating without stop ! so the code might have error so any idea how to make it stop after 5 times of repeating its movement. ~ Thanks

You don't seem to be decrementing the counter as your code implies you mean to do:

counter--;

Here's the full function:

function rollClouds() 
{
    // decrement (decrease) the counter otherwise it's never less than 1

    document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
    g--;
    if (counter < 1) {
        clearInterval(interval);
    }
    counter--;
}

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