最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Time delay on click - Stack Overflow

programmeradmin5浏览0评论

Can anyone send me JavaScript code on how I can construct a time delay from the time I click a button on a page to the time the function called by the button click is executed. I am a novice with JavaScript, and I have some code that performs a function when I click a button, and I just want to have a time delay.

Can anyone send me JavaScript code on how I can construct a time delay from the time I click a button on a page to the time the function called by the button click is executed. I am a novice with JavaScript, and I have some code that performs a function when I click a button, and I just want to have a time delay.

Share Improve this question edited Aug 17, 2015 at 8:05 vaultah 46.5k12 gold badges119 silver badges144 bronze badges asked Dec 22, 2008 at 18:21 aammaguiaraammaguiar 0
Add a comment  | 

4 Answers 4

Reset to default 7

This is the Javascript:

 function myfunction() {
     alert( "delayed" );
 }

 var delay = 1000;

 setTimeout( myfunction, delay )

That's the essence. Now you need to hook it into a button on a html page: embed the function definition in < script > ... < /script > tags, and schedule it in the onClick method.

....
<button onClick="setTimeout( myfunction, delay );">Click_And_Wait</button>

If you need to pass parameters:

function clickHandler(id,value,delay)
{
    setTimeout( function() { actualFunction(id, value); }, delay );
}

function actualFunction(id, value)
{
    alert( 'button ' + id + ' has value = ' + value );
}


<input id='clickButton' type='button'
       onclick='clickHandler(this.id,this.value,5000);'
       value='Click Me' />

Try the setTimeout function:

setTimeout(functionToExecute, 1000)

The first parameter is the function that will be triggered and the second is the delay in milliseconds.

I would suggest looking into Prototype.js Especially if you are new developer for JavaScript. Prototype has already figured out alot of the most common needs that JavaScript developers want to do in their code.. and Prototype does it in a Browser Independent way. (there are other JavaScript Libraries out there that can do this as well)

You can do it as coded in the other answers.. but I have found that I typically spend less effort in worrying about bugs in my code after I invested in a good Book and spent 2 days reading about Prototype (or some other Library like jQuery) versus searching the Internet and copy/pasting various bits of solutions. /shrug

发布评论

评论列表(0)

  1. 暂无评论