0

How do you set an interval inside of an event?

switch(event.keyCode) { //case(40): // if(bottom < 406) //{ // el.style.color = "black"; //el.style.top = 8 + top; //} //break; // case(38): // if(top !=0) // { // el.style.top = top - 8; //} // break; case(37): if(left > 0) { el.style.left = left - 8; } break; case(39): if(right < 512) { el.style.left = left +8; } break; case(32): //space { var intervalMain = setInterval(jump, 10); } } I go into my jump function and try to clear this interval. I get the message that intervalMain is not defined. Why is that? intervalMain is a global variable.

24th Dec 2018, 11:44 PM
Elizabeth Murphy
Elizabeth Murphy - avatar
2 Respuestas
+ 3
The variable are in the local scope, so jump function cant see it. Use anonymous function instead. or declare intervalMain somewhere else where the jump function can see it
25th Dec 2018, 12:02 AM
Taste
Taste - avatar
+ 3
Just to further elaborate Taste's answer, a short cure for you: var intervalMain; ... codes... ... codes... Your switch{ intervalMain = setInterval(); // no keyword var here } jump function{ clearInterval() } For enrichment, you need to understand an advanced JavaScript concept called Closure. Here is David Carroll's pick of 3 readings from beginner to advanced: https://www.sololearn.com/post/45261/?ref=app
25th Dec 2018, 4:07 AM
Gordon
Gordon - avatar