Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

javascript - Upon Link Click and setTimeout

In JavaScript, I am trying to execute a function 2 seconds after a link is clicked, and wait until the function completes its execution before going to the link destination.

/* JavaScript */
function myFunction() { /* Block of code, with no 'return false'. */ }

<!-- HTML -->
<a onclick="setTimeout(myFunction, 2000);" href="http://www.siku-siku.com">Link</a>

The problem is upon click, the browser immediately goes to the link destination i.e. myFunction didn't have time to execute. Did I miss anything here?

Thanks beforehand.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will need to return false from your onclick event, to cancel the actual browser handled page load.

And since you want to follow the link (once the function is complete) you will need to do that through javascript. But you are using a timeout so you loose the reference to the clicked element, so we need to pass that too in the method (if you want this logic for multiple links)

html

<a onclick="return createTimedLink(this, myFunction, 2000);" href="http://www.siku-siku.com">Link</a>

javascript

function createTimedLink(element, callback, timeout){
  setTimeout( function(){callback(element);}, timeout);
  return false;
}

function myFunction(element) { 
/* Block of code, with no 'return false'. */
  window.location = element.href;
 }

demo at http://jsfiddle.net/gaby/mdkjX/2/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...