我使用两个函数,一个将一组问题移动到下一个问题,另一个将进度条移动。将用户移至 nextQuestion
的问题会覆盖第一个函数,并且 progressBar
函数不会处理。
没有显示任何错误,我已经更改了顺序或函数,并且一个大函数都具有相同的结果。如果我单独运行这些功能,那么这两个功能都可以完美运行。它们源自按钮上的 @onClick。
我尝试使用 Promise 得到了相同的结果。
如何强制 nextQuestion
函数仅在 progressBar
完成时运行?
进度条
progressBar: function(item){
this.percentQuestion = 100/this.numberQuestions;
var elem = document.getElementById("myBar");
var numericWidth = elem.style.width.replace(/\D/g,'');
var currentWidth = +numericWidth;
var newWidth = +numericWidth + +this.percentQuestion;
var id = setInterval(frame, 10);
function frame() {
if (currentWidth < newWidth) {
currentWidth++;
elem.style.width = currentWidth + '%';
} else{
clearInterval(id);
};
};
this.nextQuestion(item);
},
下一个问题
nextQuestion: function(item){
var newKey = item + 1;
var y = document.getElementById('question' + item);
var x = document.getElementById('question' + newKey);
if( y.style.display === 'block'){
y.style.display = 'none';
x.style.display = 'block';
console.log("Changed");
};
},
更新
nextQuestion: function(item){
window.setTimeout(function() { function(item){
var newKey = item + 1;
var y = document.getElementById('question' + item);
var x = document.getElementById('question' + newKey);
if( y.style.display === 'block'){
y.style.display = 'none';
x.style.display = 'block';
console.log("Changed");
};
}, 1000);
},
最佳答案
以下内容符合您的要求吗?
progressBar: function(item){
this.percentQuestion = 100/this.numberQuestions;
var variables = {
elem: document.getElementById("myBar"),
numericWidth: elem.style.width.replace(/\D/g,''),
currentWidth: +numericWidth,
newWidth: +numericWidth + +this.percentQuestion,
};
// This isn't the nicest way of doing this but it should work
var that = this;
var id = setInterval(function(){
frame(item, variables);
}, 10);
function frame(item, variables) {
if (variables.currentWidth < variables.newWidth) {
variables.currentWidth++;
variables.elem.style.width = variables.currentWidth + '%';
} else{
clearInterval(id);
that.nextQuestion(item);
};
};
},
关于javascript - 仅允许 Javascript 函数在前一个函数完成后运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42366286/