jQuery setTimeout() Function Examples

/* setTimeout is a native JavaScript function (although it can be used with a library such as jQuery, as we’ll see later on), which calls a function or executes a code snippet after a specified delay (in milliseconds). This might be useful if, for example, you wished to display a popup after a visitor has been browsing your page for a certain amount of time, or you want a short delay before removing a hover effect from an element (in case the user accidentally moused out). */ //Syntax var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]); var timeoutID = window.setTimeout(code, [delay]); /* where: timeoutID - is a numerical id, which can be used in conjunction with clearTimeout() to cancel the timer. func - is the function to be executed. code - (in the alternate syntax) is a string of code to be executed. delay - is the number of milliseconds by which the function call should be delayed. If omitted, this defaults to 0. */ //Examples of Use //This can be the name of a function: function explode(){ alert("Boom!"); } setTimeout(explode, 2000); //A variable that refers to a function: var explode = function(){ alert("Boom!"); }; setTimeout(explode, 2000); //Or an anonymous function: setTimeout(function(){ alert("Boom!"); }, 2000); //It is also possible to pass setTimeout a string of code for it to execute: setTimeout("alert('Boom!');", 2000); //Passing Parameters to setTimout /* In a basic scenario, the preferred, cross-browser way to pass parameters to a callback executed by setTimeout is by using an anonymous function as the first argument. In the following example, we select a random greeting from a greetings array and pass this random greeting as an parameter to a greet function, which is executed by setTimeout with a delay of one second. */ function greet(greeting){ console.log(greeting); } function getRandom(arr){ return arr[Math.floor(Math.random()*arr.length)]; } var greetings = ["Hello", "Bonjour", "Guten Tag"], randomGreeting = getRandom(greetings); setTimeout(function(){ greet(randomGreeting); }, 1000); //An Alternative Method /* As can be seen from the syntax at the top of the article, there is a second method of passing parameters to a callback executed by setTimeout. This involves listing any parameters after the delay. With reference to our previous example, this would give us: */ setTimeout(greet, 1000, randomGreeting); //Cancelling a Timer /* The return value of setTimeout is a numerical id which can be used to cancel the timer in conjunction with the clearTimeout() function. */ var timer = setTimeout(myFunction, 3000); clearTimeout(timer);

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.