How to create an infinite loop in TypeScript

5 Answers

0 votes
// Infinite Loop Using while (true)

let count: number = 0;

while (true) { // infinite loop
    console.log("Iteration:", count);

    if (count === 3) {
        console.log("Breaking out of loop...");
        break;
    }

    count++;
}

console.log("Loop finished.");



/*
run:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Breaking out of loop...
Loop finished.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite Loop Using for (;;)

let count: number = 0;

for (;;) { // infinite loop
    console.log("Step:", count);

    if (count === 3) {
        console.log("Breaking out of loop...");
        break;
    }

    count++;
}

console.log("Done.");


/*
run:

Step: 0
Step: 1
Step: 2
Step: 3
Breaking out of loop...
Done.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite Loop Using do { } while(true)

let count: number = 0;

do { // infinite loop
    console.log("Count:", count);

    if (count === 3) {
        console.log("Breaking out of loop...");
        break;
    }

    count++;
} while (true); // infinite loop

console.log("Finished.");



/*
run:

Count: 0
Count: 1
Count: 2
Count: 3
Breaking out of loop...
Finished.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite Loop Using async + await

function sleep(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function main() {
    let count: number = 0;

    while (true) { // infinite loop
        console.log("Async iteration:", count);

        if (count === 3) {
            console.log("Breaking out of loop...");
            break;
        }

        count++;

        await sleep(500);
    }

    console.log("Async loop finished.");
}

main();



/*
run:

Async iteration: 0
Async iteration: 1
Async iteration: 2
Async iteration: 3
Breaking out of loop...
Async loop finished.

*/

 



answered Apr 11 by avibootz
0 votes
// Infinite Loop Using setInterval

let count: number = 0;

const id = setInterval(() => { // infinite loop
    console.log("Tick:", count);

    if (count === 3) {
        console.log("Breaking out of loop...");
        clearInterval(id);
    }

    count++;
}, 500);



/*
run:

Tick: 0
Tick: 1
Tick: 2
Tick: 3
Breaking out of loop...

*/

 



answered Apr 11 by avibootz
...