【发布时间】:2018-05-28 06:12:32
【问题描述】:
我需要使用多个参数多次调用一个函数。我希望在上一次调用的超时完成后调用它。我尝试了以下方法,但似乎无法正常工作。 (Here's the JSFiddle)。
现在它只在第一次通话后等待。我知道这不是正确的方法,但我找不到任何正确显示如何做的例子。我还需要将其转换为typescript,因此请在回答时考虑这一点。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="call()">Call all methods</button>
<script>
var myVar;
function call(){
myFunction('normal1','heading1','message1');
myFunction('normal2','heading2','message2');
myFunction('normal3','heading3','message3');
/*Output should be:
(first time dont wait)
heading1 message1
(then wait for timeout and remove the elements)
heading2 message2
(then wait for timeout and remove the elements)
heading3 message3
*/
}
function myFunction(msgType,heading,message) {
console.log(!!document.getElementById("snackbarParent"),document.getElementById('snackbarParent'));
if(document.getElementById("snackbarParent") == null)
{
alertFunc(msgType,heading,message);
}
else{
setTimeout(function(){
let parent = document.getElementById('snackbarParent');
parent.parentNode.removeChild(parent);
alertFunc(msgType,heading,message);
},3500);
}
}
function alertFunc(msgType,heading,message) {
let div = document.createElement('div');
div.className = 'snackbarParent';
div.id = "snackbarParent";
div.innerHTML = '<div id="snackbar"><b style="color:' + msgType + '"> ' + heading + ' </b>' + message + '</div>';
document.documentElement.appendChild(div);
// Get the snackbar DIV
let x = document.getElementById("snackbar");
// Add the "show" class to DIV
x.className = "show";
setTimeout(function(){
x.className = x.className.replace("show", "");
alert("Should display "+heading+" "+message+" now!");
}, 3000);
}
</script>
</body>
</html>
注意:
函数 call() 仅用于表示目的。参数可以是任意值,函数myFunction()可以随时随地调用。
【问题讨论】:
-
制作一个循环.. 您现在只使用 1 个函数,这会在再次遍历整个循环之间产生延迟。你现在的函数是,1(等待 3 秒)1-2(等待 3 秒)1-2-3
-
不要从
call函数调用myFunction三次。从那里只调用一次,另外两次从alertFunc函数中的setTimeout回调调用(换句话说,使用递归)。 -
@Titus @Tomm 函数
call()仅用于表示。可以有任意数量的对myFunction()的调用。我想将此功能导入另一个项目。
标签: javascript html typescript settimeout