如何清除在函数中设置的 javascript 超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8755011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:29:26  来源:igfitidea点击:

How to clear a javascript timeout thats set within a function

javascriptsettimeout

提问by Talon

I have a recursive type function in Javascript that runs like this:

我在 Javascript 中有一个递归类型函数,它运行如下:

function loadThumb(thumb) {
    rotate=setTimeout(function() {
        loadThumb(next);
    }, delay);
}

Note: I've simplified the function to make it easier to read.

注意:我已经简化了函数以使其更易于阅读。

I have "a" tags called like this

我有这样称呼的“a”标签

<a href="#" onclick="loadThumb(3); clearTimeout(rotate);">Load thumb 3</a>

However, they don't clearout the timer, the timer continues to cycle through the function irregardless of the clearTimeout()being called.

但是,它们不会清除计时器,无论clearTimeout()是否被调用,计时器都会继续循环执行该函数。

Any ideas why? I think it might have something to do with a scope problem or something like that.

任何想法为什么?我认为这可能与范围问题或类似问题有关。

回答by benesch

Yeah, you need to make rotate a global variable. Simply declare it outside the function like so:

是的,你需要让rotate成为一个全局变量。简单地在函数外声明它,如下所示:

var rotate;
var delay = 1000;

function loadThumb(thumb) {
    alert("loading thumb: " + thumb);
    rotate = setTimeout(function() {
        loadThumb(thumb + 1);
    }, delay);
}

Also, you need to make sure you clear the timeout beforeyou call loadThumb. Otherwise you'll clear the timer you just started.

此外,您需要确保调用之前清除超时loadThumb。否则,您将清除刚刚启动的计时器。

<a href="#" onclick="clearTimeout(rotate); loadThumb(3);">Load thumb 3</a>

fiddle: http://jsfiddle.net/63FUD/

小提琴:http: //jsfiddle.net/63FUD/

回答by Hemant Metalia

it may be the issue of scope so make rotate as global variableand call clearTimeout(rotate);

这可能是作用域的问题,所以将旋转作为全局变量并调用clearTimeout(rotate);

refer clearTimeout() example

参考clearTimeout() 示例

回答by James Wiseman

It may be a scoping issue if you are not declaring rotateexternally.

如果您不rotate对外声明,这可能是一个范围界定问题。

Try this:

试试这个:

var rotate = 0;
function loadThumb(thumb) {

    rotate=setTimeout(function() {
        loadThumb(next);
    }, delay);

}

回答by Krasimir

I'm not sure what exactly you are doing, because as far as I can see you didn't post all the code, but this looks better for me:

我不确定你到底在做什么,因为据我所知你没有发布所有的代码,但这对我来说看起来更好:

function loadThumb(thumb) {

    return setTimeout(function() {
        loadThumb(next);
    }, delay);

}

and then:

接着:

<a href="#" onclick="clearTimeout(loadThumb(3));">Load thumb 3</a>

回答by mplungjan

Return false on the link

在链接上返回 false

Since you are not using var rotate, it should not be a scoping issue since rotate would be in the window scope. Can you show the complete code?

由于您没有使用 var rotate,它不应该是一个范围问题,因为 rotate 将在窗口范围内。你能显示完整的代码吗?

It is considered poor coding to inline the script - you should attach the event handler onload of the page

内联脚本被认为是糟糕的编码 - 您应该在页面加载时附加事件处理程序

Also you should not have the setTimeout inside a function that might be called for one image

此外,您不应该在可能为一张图像调用的函数中使用 setTimeout

Try this:

试试这个:

var rotate,next=1;
function loadThumb(thumb) {
  if (thumb) ... use thumb
  else ... use next
}

function slide() {
    rotate=setInterval(function() {
        loadThumb();
        next++; 
        if (next>=images.length) next=0;
    }, delay);
}

window.onload=function() {
  var links = document.getElementsByTagName("a");
  if (links[i].className==="thumbLink") {
    links[i].onclick=function() {
      var idx = this.id.replace("link","");
      loadThumb(idx);
      clearInterval(rotate);
      return false;
    }
  }
  document.getElementById("start").onclick=function() {
    slide();
    return false;
  }
  document.getElementById("stop").onclick=function() {
    clearInterval(rotate);
    return false;
  }
  slide();
}

assuming

假设

<a href="#" id="start">Start</a>
<a href="#" id="stop">Stop</a>

<a href="#" id="link0" class="thumbLink">Show 1</a>
<a href="#" id="link1" class="thumbLink">Show 2</a>
<a href="#" id="link2" class="thumbLink">Show 3</a>

回答by Michael Alexander Freund

If you have to manage multiple timeouts, you can use an object in the global scope and some custom methods to create and remove your timeouts. To access the methods you can either put the calls in the onclick handler of your links (like in the example), or use a library like jQuery to bind them.

如果您必须管理多个超时,您可以使用全局范围内的对象和一些自定义方法来创建和删除您的超时。要访问这些方法,您可以将调用放在链接的 onclick 处理程序中(如示例中所示),也可以使用 jQuery 之类的库来绑定它们。

<script type="text/javascript">
    var timeouts = timeouts || {};

    function createTimeout(name, milliseconds, callback) {
        timeouts.name = setTimeout(callback, milliseconds);
    }

    function removeTimeout(name) {
        if (typeof(timeouts.name) !== undefined) {
            clearTimeout(timeouts.name);
            timeouts.name = undefined;
        }
    }

    createTimeout('foo', 5000, function() {
        alert('timeout')
    });
</script>

i have also posted an example on jsFiddle http://jsfiddle.net/AGpzs/

我还在 jsFiddle http://jsfiddle.net/AGpzs/上发布了一个示例