[英]javascript wait specific amount of time before executing a function
有什么辦法可以延遲javascript中的功能嗎?
function showLabel(){
document.getElementById(id).show();
wait(5000); //wait 5 sec
document.getElementById(id).hide();
}
如果要調用此功能,我想顯示一個標簽5秒鍾,可能還有另一種方法。
注意:我不能使用jQuery
提示:使用setTimeout
window.setTimeout("javascript function", milliseconds);
閱讀文檔並了解如何執行此操作: https : //developer.mozilla.org/en/docs/Web/API/window.setTimeout
如果您想要睡覺之類的東西,請:
function sleep(millis, callback) {
setTimeout(function()
{ callback(); }
, milliseconds);
}
我更喜歡:
function doStuff()
{
//do some things
setTimeout(continueExecution, 10000) //wait ten seconds before continuing
}
function continueExecution()
{
//finish doing things after the pause
}
另一種使用循環的方式
<script type="text/javascript">
// bad implementation
function sleep(milliSeconds){
var startTime = new Date().getTime(); // get the current time
while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}
</script>
您可以嘗試以下方法:
function showLabel(){
document.getElementById(id).show();
setTimeout(function()
{
document.getElementById(id).hide();
}, 5000);
}
將setTimeout
用於一次任務,否則將setInterval
用於重復任務。
setTimeout(
function(){ Your_function }, milliseconds
);
在給定時間結束后,將調用該函數。
在javascript中使用setTimeout
函數。 並清除超時功能調用
var timerId = setTimeout(function showLabel(){
document.getElementById(id).show();
document.getElementById(id).hide();
}, 5000);
clearTimeout(timerId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.