Search code examples
javascriptclosuresinnertext

Can't write to textContent property inside javascript callback


everyone!

I develope simple script and faced to with next problem: I try reassign element.innerText property inside callback function, but nothing happens.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS Countdown</title>
</head>
<body>
    <span class="countdown">00:01:00</span>
    <span class="test">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!!!!!!!!!!!!!!!!!</span>
    <script>

        let counter = 134; // number of seconds
        let countdown =  document.querySelector('.countdown'); // where time content located


        // timer function 
        // duration of timer
        // countdown = element where put content
        !function timer(duration, countdown) {

            // run loop
            let id = setInterval(function () {
                if( duration === 0 ) {
                    clearInterval(id);
                    console.log("Timer with id #" + id +  " stopped!");

                    // when loop ends I want to paste some text into tag
                    // but nothing happen
                    countdown.textContent = "Loop ends!"; 
                }

                countdown.innerText = duration--; // this works fine and content of tag updates on 
                // every loop

            }, 10);
        }(counter,countdown); // run



    </script>
</body>
</html>

So, how can I change value of the outer tag from setInterval callback?


Solution

  • Put a return after writing the text, otherwise your code will proceed further and overwrite the text value.

    <script>
    
        let counter = 134; // number of seconds
        let countdown =  document.querySelector('.countdown'); // where time content located
    
    
        // timer function 
        // duration of timer
        // countdown = element where put content
        !function timer(duration, countdown) {
    
            // run loop
            let id = setInterval(function () {
                if( duration === 0 ) {
                    clearInterval(id);
                    console.log("Timer with id #" + id +  " stopped!");
    
                    // when loop ends I want to paste some text into tag
                    // but nothing happen
                    countdown.textContent = "Loop ends!"; 
                    return;
                }
    
                countdown.innerText = duration--; // this works fine and content of tag updates on 
                // every loop
    
            }, 10);
        }(counter,countdown); // run
    
    
    
    </script>