How to change text in real-time

Options

I would like to make a one minute countdown, which can display real-time or how many seconds

Best Answer

  • audun
    audun Posts: 302 🔥🔥🔥
    #2 Answer ✓
    Options

    Hi @bowen wang,
    I created a script that takes two arguements.
    1) Text component to update
    2) Time (in seconds)

    Code below.

    //@input Component.Text myText
    //@input int time {"label":"Time", "min":0, "max":9999, "step":1}
    
    var startTime = 0;
    var countdownTime = 0;
    var countdownInterval = null;
    
    function startCountdown() {
        if (countdownInterval != null) {
            return;
        }
    
        startTime = getTime();
        countdownTime = script.time;
        updateCountdown();
    }
    
    function stopCountdown() {
        if (countdownInterval != null) {
            countdownInterval = null;
        }
        // do something here when it reaches 0
        script.myText.text = "Wohooo!";
    }
    
    function updateCountdown() {
        var remainingTime = countdownTime - (getTime() - startTime);
        if (remainingTime < 0) {
            stopCountdown();
        } else {
            var minutes = Math.floor(remainingTime / 60);
            var seconds = remainingTime % 60;
            var countdownString = ("00" + minutes).slice(-2) + ":" + ("00" + seconds).slice(-2);
            script.myText.text = countdownString;
    
            countdownInterval = script.createEvent("DelayedCallbackEvent");
            countdownInterval.bind(updateCountdown);
            countdownInterval.reset(1);
        }
    }
    
    function getTime() {
        return Math.floor(Date.now() / 1000);
    }
    
    var event = script.createEvent("TapEvent");
    event.bind(startCountdown);
    

    The last part of the code is what triggers the countdown. In this case we start the countdown when you tap the screen.

    You can click here to see all the events available.

Answers

  • audun
    audun Posts: 302 🔥🔥🔥
    edited April 2023 #3
    Options

    Hi,
    For some reason it wouldn't let me post the comment here, so I created a discussion thread instead.

    Link to thread