Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay calling of javascript function?

I'm new to JavaScript.

I would like to call JavaScript / jQuery function after the page load in aspx page.

I tried using <form onload="function()"> and window.load = function(){}, but the JavaScript is still trigger before some of the content fully loaded.

Is it possible to call during Page_PreRender in aspx page and not in code behind, so that I can delay the JavaScript function ?

I tried setTimeout("function()",5000) to solve the problem.

However setTimeout() seem like is not compatible with some browser, e.g: caused looping in Google Chrome.

like image 576
sams5817 Avatar asked Apr 06 '11 16:04

sams5817


People also ask

How do you pause a JavaScript function?

Sleep() With the help of Sleep() we can make a function to pause execution for a fixed amount of time. In programming languages such as C and Php we would call sleep(sec).

Can JavaScript function run after delay?

Use setTimeout() inbuilt function to run function after a delay in JavaScript. It's plain JavaScript, this will call your_func once, after fixed seconds (time).

What is delay () in JavaScript?

Conclusion. setTimeout() is a method that will execute a piece of code after the timer has finished running. let timeoutID = setTimeout(function, delay in milliseconds, argument1, argument2,...); The delay is set in milliseconds and 1,000 milliseconds equals 1 second.

How do you delay 1 second in JavaScript?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.


1 Answers

setTimeout is compatible with all browsers since 1996. You should avoid the evaluation of "functionName()" and instead do:

setTimeout(functionName,5000) 

UPDATE: If you initially expect a variable passed to the function and none when in the timeout, you need to do this instead:

setTimeout(function() { functionName() },5000) 

However you are calling the onload incorrectly, so you need to do either this:

window.addEventListener("load",function() {   // your stuff } 

or the simpler

window.onload=function() {   // your stuff } 

or, since you are using jQuery, this:

$(document).ready(function() {     // your stuff }); 

or just this:

$(function() {     // your stuff }); 
like image 106
mplungjan Avatar answered Oct 11 '22 19:10

mplungjan