More info regarding your electromagnet needed - probably info you don't have! Connecting a diode across the ends of the coil gives the current a path, so that it doesn't die too fast. Normally, it's reverse-biased, so no current flows through it, but when you disconnect the voltage - switch off you...