February 23, 2010
Here's a little snippet to add a little delay before calling a function. The delayTime is set in milliseconds (500 = half a second). This can be very useful for hovering menus etc.<script type="text/javascript">
var timeOut;
var delayTime = 500;
function delayedCall(t) {
timeOut = setTimeout(function() { alert(t); }, delayTime);
}
function removeDelayedCalls() {
try {
clearTimeout(timeOut);
}
catch(ex) { }
}
</script>
You would most likely change the function call in delayedCall, how cool an alert ever can be ;). Also you might want to expand the parameter lists. I've added one just to show how they could be passed down to your final function.
Here is a sample implementation on a HTML anchor element, when hovered waits 0.5 seconds before showing the alert. If the user during this time removes the mouse pointer from the link it cancel the delayed call by calling the removeDelayedCalls function:
<a onmouseover="delayedCall('Hello world');" onmouseout="removeDelayedCalls();">Say hello</a>
Comments
comments powered by Disqus