I just wanted to know how does EOS know when a transaction is having an infinite loop like in Ethereum where there is a way that execution stops for a smart contract where it runs out of gas.?
Max CPU usage of accounts
Like @RajatChaudhary said the DPoS of EOS lets you stake tokens for the CPU usage of your account. If you exceed this the transaction will be canceled. Same goes for RAM or bandwith. So staking your tokens is the equivalent of gas usage in Ethereum. Difference is that you get the tokens back and do not burn them. You pay by the annual inflation in the block reward system.
Transaction time limit
Another thing to consider is the transaction timelimit which is related to the block time of the DPoS Consensus Algorithm.
While blocks are produced turnwise by the blockproducers with a rate of 0.5 sec at the moment a transaction time limit of 150ms will prevent inifinite loops. This is related to prevent blockproducers missing block turns and provide high speed and transaction throughput.
If you want to run high ressource tasks like infinite loops for CPU, spamming for RAM or bandwith, the staking of tokens or the transaction time limit will prevent you from hurting the system.
Your account has fixed CPU usage which you can check by using
cleos get account <your-account-name> -j command. In case of a while loop, when the CPU usage will get exhausted fully, your transaction will stop and it will throw the error which will be like
Transaction exceeded the current CPU usage limit imposed on the transaction.
When you cleos get block one of the JSON fields returned for each transaction in the block is cpu_usage_us, which is CPU time in microseconds used to execute the transaction
The reference for the above statement is here.