It’s highly likely that the boot HDD is failing.
If you have another compatible Mac, you can set the iMac to boot from the 2nd Mac via Target Disk Mode to see how the iMac works, and backup/transfer useful files and apps by Time Machine or file/folder copy.
Otherwise, you can try to boot into single user mode by pressing Cmd+S, and log in to this text based environment. After that, you can run a few disk diag commands, such as
/sbin/fsck -fy
Then if it verifies that the HDD is failing, you may consider reinstall and migrate the OS to an external USB/TB disk. An SSD is recommended.
Overall, the most common problems for iMacs are HDDs. Over the years from 2007 I have experienced 2 painful HDD failures.