简体   繁体   English

我莫名其妙地无法停止我的setTimeout()循环

[英]I somehow can't stop my setTimeout() loop

So i have a major function which triggers another function every 2 - 17 seconds but when I try to stop it with clearTimeout() it just goes on and completely ignores the clearTimeout() . 因此,我有一个主要function ,每clearTimeout()秒触发一次其他function但是当我尝试使用clearTimeout()停止它时,它将继续运行,并且完全忽略clearTimeout()

So this is my major function: 这是我的主要功能:

var itemTimer;
var stopTimeout;

function major (){
    var itemTime = Math.floor(Math.random() * 15000) + 2000;
    itemTimer = setTimeout('items()', itemTime);    
    stopTimeout = setTimeout('major()',itemTime);
}

And this is my stop timeout function: 这是我的停止超时功能:

function stopTimer() {
    clearTimeout(itemTimer);
    clearTimeout(stopTimeout);
}

Thank you for helping 感谢您的帮助

Your setTimeout() is being called incorrectly; 您的setTimeout()被错误地调用; you're invoking items() and major() . 您正在调用items()major() Instead, you need to pass them as functions to be invoked. 相反,您需要将它们作为要调用的函数传递。

Don't pass the brackets to the parameters, and don't wrap the parameters in quote marks. 不要将方括号传递给参数,也不要将参数用引号引起来。

Instead of: 代替:

itemTimer = setTimeout('items()', itemTime);    
stopTimeout = setTimeout('major()',itemTime);

You're looking for: 您正在寻找:

itemTimer = setTimeout(items, itemTime);
stopTimeout = setTimeout(major, itemTime);

Hope this helps! 希望这可以帮助! :) :)

I think your timeouts are stacking up. 我认为您的超时时间越来越长。 As soon as major gets called once, the variables itemTimer and stopTimeout get reassigned a new timeout reference. 只要major被调用一次,变量itemTimerstopTimeout得到重新分配一个新的超时参考。 So there will be no way to clear the timeouts that were previously set. 因此,将无法清除先前设置的超时。 If this is the case it should be an easy fix though. 如果是这种情况,则应该很容易解决。 Just call stopTimer as very first statement in major : 只需将stopTimer作为major第一个语句调用即可:

function major (){
    stopTimer();
    var itemTime = Math.floor(Math.random() * 15000) + 2000;
    itemTimer = setTimeout('items()', itemTime);    
    stopTimeout = setTimeout('major()',itemTime);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM