我已经创建了一个网站。当用户首次打开它时,javascript调用(showDetails()
)一个函数(在后端执行一些任务),当用户按下相同功能时,我还更新了网站中的按钮将再次被调用(showDetails()
),并执行相同的任务。
但是这里的问题是,当用户按下更新按钮时,将创建showDetails的另一个实例,并且两个实例将在后台执行。 (如果用户按5次更新,则将创建showDetails()
函数的5个实例。)
我试图通过将函数分配给变量并将其销毁来解决此问题:
//creating variable
var variShow = null;
//calling showdetails() when user opens the site and assigning it to variable variShow
variShow = showdetails();
//when user presses update button checking whther variShow is null or not. if not null assign it to null and call showdetails() again.
if (variShow !== null) {
variShow = null;
}
variShow = showdetails();
但是它仍然不起作用,我该如何解决呢?
答案 0 :(得分:2)
这是解决方案: 您可以使用flag来做到这一点,但是最好在最后使用override!
var showDetails = function() {
console.log("Active method!")
// function
// your code here
// Override self
showDetails = function(){console.log("not active any more")}
}
// Just for test
showDetails();
// Just for test again
showDetails();
我们重写函数以使通话不做任何操作(空):
showDetails = function(){}
然后,您将避免在其他调用showDetails()时出错;
如果您输入:
showDetails = null;
然后将产生“ showDetails()”错误。您可以将其设置为null或
showDetails = undefined;
但是您必须在拨打电话之前进行检查:
// This is strong check work on all old and new browsers
if (typeof showDetails !== 'undefined' && typeof showDetails === "function") {
showDetails()
}
var showDetails = function() {
console.log("Active method!")
// function
// your code here
showDetails = undefined;
// modern js
// delete showDetails
}
// First time call
showDetails();
// This is strong check work on all old and new browsers
if (typeof showDetails !== 'undefined' &&
typeof showDetails === "function") {
// Second call must be protected/checked
showDetails()
} else {
console.log("Not active method!");
}
答案 1 :(得分:0)
var interrupted = false;
function showDetails(){
interrupted = false;
//Some task
//...
//Check if someone interrupt the function at some point of the function
if(interrupted){
//Some code to handle interruption here
//...
interrupted = false;
return;
}
//Some task
//...
interrupted = false
}
当用户进入页面时
showDetails();
当用户按下按钮时
interrupted = true;
var waitInterval = setInterval(function(){
//Wait until the running function to be terminated.
if(!interrupted){
clearInterval(waitInterval);
showDetails();
}
}, 100)