A Guide to Discord Bots

Timeouts/Intervals (Timers)

Let's say you want a function or part of code to execute in x seconds, or each x seconds.
This is exactly what timeouts and intervals are for!
They are built-in methods and can be used just like that.

// Execute getData() in 5000 milliseconds, which is 5 seconds
setTimeout(getData(), 5000);

setTimeout(() => {
    // Unnamed functions work too
    console.log('Executed after 2 seconds.');
}, 2000);

// Execute getData() every 10 seconds
setInterval(getData(), 10000);

function getData() {
    // fetch some data
    console.log('getData() executed!');
    return;
}

But if you want to be able to cancel a timeout or an interval, you need to use clearTimeout() or clearInterval().

var inFiveSeconds = setTimeout(getData(), 5000);
clearTimeout(inFiveSeconds);

var everyFiveSeconds = setInterval(getData(), 5000);

function getData() {
    // fetch some data
    console.log('getData() executed!');

    // Make sure that the variable is defined in this scope!
    clearInterval(everyFiveSeconds);
    return;
}

results matching ""

    No results matching ""