如何调用将持续 2 秒的函数

How to call function that will last 2 seconds?

本文关键字:函数 何调用 调用      更新时间:2023-09-26

我需要在单击时调用微调器,它需要显示 2 秒然后消失。我不能使用 setTimeout 和 setInterval...还有其他功能吗?

好的,这里有一个使用 setTimeout 的快速示例。

.HTML

<button>Click me</button><br>
<div id="spinner">I am a spinner</div>

.CSS

#spinner {
    display: none;
}

JavaScript

// pick up the elements to be used
var button = document.querySelector('button');
var spinner = document.querySelector('#spinner');
// add an event to the button so that `showThing` is run
// when it is clicked
button.onclick = showThing;
// `showThing` simply displays the spinner and then
// calls `removeThing` after 2 seconds
function showThing() {
  spinner.style.display = 'block';
  setTimeout(removeThing, 2000)
}
// and `removeThing` removes the spinner
function removeThing() {
  spinner.style.display = 'none';  
}

演示

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

回复:你对setTimeout()的评论

要只使用 setTimeout 一次...

setTimeout(myfunction(), 2000);

您可以尝试设置 CSS 动画来执行此操作。CSS动画的解释可以在这里找到:

https://css-tricks.com/almanac/properties/a/animation/

或者使用如下所示的设置超时:

Javascript:

$('#something').hide();
$('#clicky').on('click', function () {
   $('#something').show();
    setTimeout(function () {
        $('#something').hide();
    }, 2000);
});

.HTML:

<button id="clicky">Click me</button>
<p id="something">Boo!</p>

http://jsfiddle.net/jonnyknowsbest/kkqqjz0v/