简体   繁体   中英

Two events fire the same function

This anonymous function is fired by mouse movement.

var timeout;

// onkeypress

document.onmousemove = function(){
  clearTimeout(timeout);
  timeout = setTimeout(function(){alert("move your mouse");}, 1000);
}

Can I get it to be fired on key press as well? Or is the only way to do this efficiently defining the function as a named function and calling it like this:

document.onmousemove.namedfunction();
document.onkeypress.namedfunction();

JSFIDDLE

You can do it almost the same way you're doing it right now:

var timeout;

document.onmousemove = document.onkeypress = function(){
  clearTimeout(timeout);
  timeout = setTimeout(function(){alert("move your mouse");}, 1000);
}

However, reusing the same function multiple times is probably justification for giving it a name and just referencing it.

You could leave it anonymous...

document.onmousemove = document.onmousemove = function(){

But, I wouldn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM