Search code examples
javascriptfunctionsettimeoutinnerhtml

How to call a function 10 seconds after calling another function?


I have two functions, functionOne() and functionTwo().

How can I go about calling functionTwo() 10 seconds after functionOne() ends/is called?

I'd like functionOne to occur after a button is clicked, and then functionTwo 10 seconds after functionOne ends (without the need to click a button again/have the user do anything!)!

See below for my code!

<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>    

<script>
    
    functionOne() {
        document.getElementById("paragraphChange").innerHTML = "Bye World";
    }

    functionTwo() {
        document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
    }
    
</script>

I tried to use setTimeout, but the problem is that I don't think there is an 'onend' event I can use for the first function. Eg:

setTimeout(functionOne.onend, 10,000);


Solution

    1. Most importantly you have to declare your functions properly using the function keyword: function functionOne, function functionTwo.

    2. Here's the documentation for setTimeout: "The global setTimeout() method sets a timer which executes a function... once the timer expires." So you pass in the function that you want to execute once the timer has completed.

    And here are some more methods of approaching the problem.

    1. Cache your paragraph element along with the button up front so you're making the code as DRY as possible.

    2. Move the inline JS to the script, and use addEventListner to the para element

    3. Use textContent instead of innerHTML because you're not adding HTML

    // Cache the elements
    const para = document.querySelector('#paragraphChange');
    const button = document.querySelector('#clickToChangeText');
    
    // Add a listener to the button
    button.addEventListener('click', functionOne, false);
    
    // Set the text content of the para element
    // and then call the second function with a time out
    function functionOne() {
      para.textContent = 'Bye World';
      setTimeout(functionTwo, 5000);
    }
    
    // Update the para with new text
    function functionTwo() {
      para.textContent = 'Jokes I\'m still here';
    }
    <p id="paragraphChange">"Hello World"</p>
    <button type="button" id="clickToChangeText">Click!</button>