Search code examples
javascripthtml

Is there a way to wait for a function to finish before running it again?


I stumbled across this problem when i was trying to make an animation using JavaScript, and the animation itself turned out fine. The problem was, if you were to run the animation multiple times in a row (using a button), the function would run multiple times even if the first animation wasn't finished. Here is my example:

var x = 1;
function test() {
    if(x == 1) {
        x == 0;
        document.getElementById("test").innerHTML = "I was clicked.";
        setTimeout(() => {x == 1;}, 5000);
    }
    else {
        document.getElementById("test").innerHTML = "You already clicked me!";
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p onclick="test()" id="test">click me</p>
    <script src="test.js"></script>
</body>
</html>

Solution

  • You just need to add a few lines to prevent the function from being launched before the current execution finishes.

    var x = 1;
    var isRunning = false;  
    
    function test() {
          // If it is running (therefore "isRunning" is true we exit the function
        if( isRunning ) return;
       
          // If we enter the body of the function, we set 
          // "isRunning" to true, to avoid other executions
        isRunning = true;
        if(x == 1) {
            x == 0;
            document.getElementById("test").innerHTML = "I was clicked.";
            setTimeout(() => {x == 1;}, 5000);
        }
        else {
            document.getElementById("test").innerHTML = "You already clicked me!";
        }
    
          // Once the execution is finished, we change "is Running" to false,
          // leaving the path free for another execution
        isRunning = false;
    }