user3733929
user3733929

Reputation: 47

How to block many run function JS

i try show some text in function after this i want to wait 3 seconds and next i want run other functions. My pseudo code is:

showText();
wait 3 seconds
showSecondText();
showOtherText();

And now i wrote:

function helloOnClick(){
showText();
var myVar = setInterval(function(){showSecondText(data); showOtherText(data); clearInterval(myVar); },3000);
}

And now is almost perfect but when i click button and run helloOnClick() many times my functions showSecondText() will be run over and over becouse setInterval create many instance becouse clearInterval kills only one ?

How resolve this task ? I have two possibilities: 1. I can disabled button when function helloOnClick will be clicked and for end i can enabled 2. When click i can set flag on true and after finish change on false. When flag will be tru unction will not run.

What will be best choice ?

Upvotes: 0

Views: 44

Answers (2)

plalx
plalx

Reputation: 43728

You can use setTimeout and you should probably extract the showing text process in it's own function, allowing to pass in a callback when the process is completed.

E.g.

function helloOnClick() {
    yourButton.disabled = true;

    startShowingText(function () {
        yourButton.disabled = false;
    });
}

function startShowingText(completed) {
    showText();

    setTimeout(function () {
        showSecondText();
        showOtherText();
        completed && completed();
    }, 3000);
}

Upvotes: 1

MightyPork
MightyPork

Reputation: 18881

You want setTimeout(), not setInterval().

Interval is a loop, timeout a delay.

Upvotes: 1

Related Questions