Javascript 如何调用将持续2秒的函数?
我需要在单击时调用微调器,它需要显示2秒然后消失。我不能使用setTimeout和setInterval…还有其他功能吗?您可以尝试设置CSS动画来完成此操作。CSS动画的解释可在此处找到: 或者使用如下设置超时: Javascript:Javascript 如何调用将持续2秒的函数?,javascript,jquery,Javascript,Jquery,我需要在单击时调用微调器,它需要显示2秒然后消失。我不能使用setTimeout和setInterval…还有其他功能吗?您可以尝试设置CSS动画来完成此操作。CSS动画的解释可在此处找到: 或者使用如下设置超时: Javascript: $('#something').hide(); $('#clicky').on('click', function () { $('#something').show(); setTimeout(function () { $(
$('#something').hide();
$('#clicky').on('click', function () {
$('#something').show();
setTimeout(function () {
$('#something').hide();
}, 2000);
});
HTML:
点击我
嘘
好的,下面是一个使用
setTimeout
的快速示例
HTML
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';
}
也许可以解释为什么不能使用setTimeout或setInterval。我如何设置该函数,使其在单击时调用一次并持续2秒…因为我知道setTimeout函数类似于delay和setInterval,每X次调用一次函数…我说得对吗?我想这会对您有所帮助。fadeOut()@无您可以只调用setTimeout一次,查看我的答案。您显示微调器,然后在2秒后使用
setTimeout
将其删除。请不要使用字符串作为setTimeout的第一个参数。使用setTimeout(callbackFn,123)
或设置超时(function(){callbackFn();},123)
而不是.Thx。每天学习新东西。:)这样,您可以直接调用它,而不是引用它。不要使用CSS动画来超时。问题在于采用一种本地javascript方式。如果这只是一个关于如何使用setTimeout的问题,那将是1000个其他问题的重复。对于给出选项,许多人表示歉意。OP用于显示视觉元素2秒钟,然后使其消失。当我读到这个问题的时候,我一定是漏掉了“native”这个词。是的,但他明确地说他不想要setTimeout,CSS动画不是最好的方式。你可以用date编写一个睡眠函数。你能帮我确定他说他不想在哪里使用setTimeout吗?好的,现在读4遍。绝对不会说“本地”,绝对会说“不能使用”。现在只需浏览众多的问题编辑。。。。。。
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
setTimeout(myfunction(), 2000);
<button>Click me</button><br>
<div id="spinner">I am a spinner</div>
#spinner {
display: none;
}
// 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';
}