Were you using it wirelessly without any issues until recently? Did you change the system configuration or install updates at the same time that you first noticed the issue? Are you using a wireless Magic Mouse, and does it still work without any issues?
Try the following to see if it makes a difference:
1) Restart your iMac. Any change?
2) Open the Bluetooth System Preferences and locate the list of paired devices.
3) Click on the keyboard in the list of devices and a small gray 'x' will show up to the right of the name. Click on the 'x' and a dialog will appear asking "Are you sure you want to remove 'Magic Keyboard'?/ (or whatever you named it) Click on 'Remove' to unpair the keyboard from your iMac.
4) Make sure the keyboard power switch is on, then connect the lightning cable to the keyboard to pair it to your iMac. Once you receive a notification in the upper right of the display telling you 'Your keyboard is wirelessly connected to this Mac.' you can disconnect the Lightning cable to see if the issue persists after you un-paired and re-paired the keyboard.
This article provides additional information:
If your Apple wireless mouse, keyboard, or trackpad isn't working as expected - Apple Support
If you continue to experience problems I suggest contacting Apple, or taking your system in to a service provider for evaluation. Good luck, and please share how the issue is resolved so we can all learn.