Is there a sleep function in JavaScript that will stop the code execution? I would like the JS execution to delay/pause/sleep for a specified period of time during the execution of a link object’s onclick event. I need this period of time in order to record Web Analytic’s data.
Steps I need are
- execute onclick event handler of a link
- execute JS assigned to onclick event of link object
- execute web analytics functions to record data
- delay JS execution to allow for web analytics data to be recorded
- return to normal link execution
I found this function on the internet (forgot where) to do this so I wanted to share it…BTW this page has interesting discussion on this http://www.daniweb.com/forums/thread47199.html
/**
* USE WISELY! It stops ALL JS execution in the browser (unlike the JS native
* settimeout function) for a period of time specified in milliseconds.
*
* This function's original intent is to be used
* with onclick event functions in order to pause/delay JS execution
* in order to ultimately delay a link's default action.
*
* 1 second is 1,000 milliseconds
*
* @param {Object} milliseconds
*/
sleep = function(milliseconds) {
var dt = new Date();
while ((new Date()) - dt <= milliseconds) {
/* Do nothing */
}
};
Just call this at any point to pause the JS execution