Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript clearInterval当setInterval完成整个执行时_Javascript_Node.js_Setinterval_Clearinterval - Fatal编程技术网

Javascript clearInterval当setInterval完成整个执行时

Javascript clearInterval当setInterval完成整个执行时,javascript,node.js,setinterval,clearinterval,Javascript,Node.js,Setinterval,Clearinterval,我使用clearInterval在调用函数时停止setInterval的执行 var myVar; function myFunction() { myVar = setinterval(function(){ alert("Hello"); }, 3000); } function myStopFunction() { clearInterval(myVar); ... } 但问题是clearInterval不会等到setInterval完成后才执行整个代码。。。

我使用clearInterval在调用函数时停止setInterval的执行

var myVar;

function myFunction() {
    myVar = setinterval(function(){ alert("Hello"); }, 3000);
}

function myStopFunction() {
    clearInterval(myVar);
    ...
}
但问题是clearInterval不会等到setInterval完成后才执行整个代码。。。。因此,我有一个错误。 我该怎么做?(如果可能的话)

var-myVar;
函数myFunction(){
myVar=setInterval(函数(){
console.log(“你好”);
净距(myVar);
}, 3000);
}

myFunction()您还需要将停止后的代码放入回调中。您可以在开始下一次迭代之前检查是否已设置了此选项,然后在间隔回调中再次检查

var myVar;
var stopCallback = null;
var processing = false;

function myFunction() {
    myVar = setInterval(function(){
        processing = true; // don't let the finishStopping() code run yet
        alert("Hello");
        someOperationWithCallback(function() {
            /* inside your deepest level of callback */
            processing = false;
            if (stopCallback) finishStopping();
        });
    }, 3000);
}

function myStopFunction() {
    stopCallback = function() {
        /* work to do after stopping */
    };
    if (!processing) finishStopping();
}

function finishStopping() {
    clearInterval(myVar);
    stopCallback();
    stopCallback = null;
}

你能解释一下你想做什么吗?调用
setInterval()
将一个操作安排在未来给定的时间段内执行,并在该时间间隔内反复执行。如何确定进程何时“完成”?为什么不使用
setTimeout
而不是
setInterval
?我正在尝试。。。我不知道。当然,我需要设置间隔来进行循环操作。。。。但我也会在调用myStopFunction时停止它们,正如我所说的,我会在setInterval完成后停止它们。进程完成了,我的意思是setInterval中的所有代码都必须在停止之前执行。您看到了什么错误?Javascript是单线程的,所以
clearInterval()
当代码在interval函数中运行时不会运行-它将在它之前或之后运行。这将有点毫无意义-基本上您已经实现了
设置超时
您是对的,但OP询问如何清除interval。您可以在这里看到一些有用的模式。