gpt4 book ai didi

javascript - 间隔结束时使用回调

转载 作者:行者123 更新时间:2023-12-02 16:22:22 27 4
gpt4 key购买 nike

我正在制作一个树遍历程序,它使用 setInterval 为遍历设置动画。当 setInterval 运行时,我想禁用“运行遍历”按钮,这样它们就不能继续运行新的遍历。

当遍历完成并且间隔被清除时,我想重新启用按钮。 stackoverflow 的答案建议在间隔结束后使用回调调用 enableButtons...

this.traverseNodes(nodesToDraw, aryList, e.target.id, this.enableButtons);

 api.traverseNodes = function (nodesToDraw, dataStructureList, algType, enableButtonsCallback) {
...
var myInterval = setInterval (function() {
if (i >= nodesToDraw.length-1) {
matrixTraversalRunning = false;
enableButtonsCallback(dsTraversalRunning, matrixTraversalRunning);
clearInterval(myInterval);
}

这工作正常,但后来想...为什么我需要回调?我可以在间隔结束后直接调用 enableButtons,如下所示:

this.traverseNodes(nodesToDraw, aryList, e.target.id);

api.traverseNodes = function (nodesToDraw, dataStructureList, algType) {
...
var myInterval = setInterval (function() {
if (i >= nodesToDraw.length-1) {
self.enableButtons(dsTraversalRunning); //call function to enable buttons
clearInterval(myInterval);
}
...

由此,我对何时使用回调感到困惑。这里有必要吗?

最佳答案

不,没有必要。

但是,使用回调将允许您在具有不同布局的不同页面上使用相同的类进行树遍历。例如,您可能希望在一个页面上启用/禁用三个按钮,而在另一页面上仅启用/禁用一个按钮。

这是一个例子:

//First I'll create a fake tree class for performing work:
var FakeTree = function(size){
this.size = size;

//Create a fake method to simulate node traversal
var _this = this;
this.TraverseOneNode = function(){
_this.size = Math.max(_this.size - 1, 0);
return (_this.size == 0);
}
}

//Now define function for traversal
function TraverseNodes(tree, callbackfn){
var myInterval = window.setInterval( function(){
if(tree.TraverseOneNode()){
clearInterval(myInterval);
callbackfn();
}
}, 500);
}


//Now define callbacks for the two button sets:
function button_one_callback(){
//Enable button1
$('#button1').removeAttr('disabled');
}

function button_two_callback(){
//Enable button2, and buttonOK
$('#button2').removeAttr('disabled');
$('#buttonOK').removeAttr('disabled');
}


//Button onclick functions:
function button_one_click(){
//Disable button one
$('#button1').prop("disabled",true);

//Call "TraverseNodes", pass it a new FakeTree of size=5, and the callback for this button
TraverseNodes(new FakeTree(5), button_one_callback);
}

function button_two_click(){
//Disable button one
$('#button2').prop("disabled",true);
$('#buttonOK').prop("disabled",true);

//Call "TraverseNodes", pass it a new FakeTree of size=10, and the callback for this button
TraverseNodes(new FakeTree(10), button_two_callback);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button1" value="Traverse Tree 1" onclick="button_one_click()" />
<br />
<br />
<input type="button" id="button2" value="Traverse Tree 2" onclick="button_two_click()" />
<input type="button" id="buttonOK" value="OK" />

关于javascript - 间隔结束时使用回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993004/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com