var intervalID; function runtest() { keytest =keytest *(-1); if (keytest == (-1)){intervalID = setInterval(function() runfun();},3000);} if (keytest == (1)){clearInterval(intervalID);} }