简体   繁体   中英

Javascript: how to set intervals with a variable or run code once?

I have a problem with javascript because I want to run code in a function once until a interval is again over. So I have read about a possibilty to use an boolean to control it but without intervals and it is still calling the updatePosition() function over and over without stopping. Simplyfied I have code in this structure:

var runPerm = false;
function start() {
    setInterval(setPerm, 2000);
    setInterval(function() {
        new updatePosition()
    }, 2000);
}
function setPerm() {
    runPerm = true;
}
function updatePosition() {
    if (runPerm == true) {
        //some code that I want to run once.
        runPerm = false;
    }
}

Has someone an idea to solve the problem? (A full code: http://pastebin.com/iSFHjct3 )

Use setTimeout .

var runPerm = false;
function start() {
    setInterval(setPerm, 2000);
    setTimeout(updatePosition, 2000);
}

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