如何调用将持续 2 秒的函数
How to call function that will last 2 seconds?
我需要在单击时调用微调器,它需要显示 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/
相关文章:
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- Meteor Router数据函数被调用两次
- 拦截对构造函数的调用
- 为什么(如何)'这'从函数内部调用回调时发生更改
- 比较sessionStorage值时,Javascript函数无法调用
- 如何从构造函数中调用js原型方法
- 使用AJAX将变量发布到不同文件上的php函数并调用该函数
- 从构造函数es6调用静态方法
- 如何在函数中调用函数?(CoffeeScript)
- 我在画布中的鼠标按下函数在调用时不会重绘背景
- Javascript 从函数名称调用函数
- 使用函数按钮调用 ajaxform
- 调用子类函数时调用的超类函数
- 如何使用字符串作为类名并在函数中调用它
- 轮询 ajax 函数超出调用堆栈
- java-script 函数被调用两次
- 使用 Promise 在另一个函数中调用带有 Bluebird 承诺库的函数
- 更改函数名称调用中的单击事件
- 使用promise或setTimeout确定延迟函数的调用顺序
- 如何避免在函数中调用函数