2

New to Smart Contract development and am wondering if there is anyway to do a timed countdown inside a contract.

Basically I want to see if it's possible to trigger a process inside a contract that decrements or increments a value in the contract every x amount of seconds or minutes.

I wanted to see if this was possible to do internally? Or if the only way was to have some backend bot running to perform increment/decrement transactions.

Any insight is much appreciated! Thank You!

3

Rather than actually changing some variable over time, compute it on the fly.

E.g., to ask "How many seconds until x time?" you could write a function like this:

function secondsRemaining() public view returns (uint256) {
    if (x <= now) {
        return 0;  // already there
    } else {
        return x - now;
    }
}

Essentially, a contract can't do anything by itself; it needs to be invoked via a transaction. But you can lazily compute the value instead when it's needed.

1

Every change on the Ethereum blockchain is always triggered from outside by a signed transaction. Hence, there is no way to implement a reoccurring timer within the smart contract itself. You'll always need to trigger it from outside.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.