简体   繁体   English

我不明白clearInterval()

[英]I don't understand clearInterval()

I have play and skip buttons for JSON array working fine: 我有JSON数组的播放和跳过按钮可以正常工作:

jQuery: jQuery的:

$(function() {
    // Fetch the initial image
    fetchImage(index);

    // Event listeners
    $("#play").click(function() { fetchImage(next); setInterval(function() { fetchImage(next); }, 1000); return false;});
    $("#stop").click(function() { clearInterval(xxx); return false;});
    $("#prev").click(function() { fetchImage(prev); return false;});
    $("#next").click(function() { fetchImage(next); return false;});
});

xxx should preferably be a variable I read. xxx应该最好是我读取的变量。 setInterval() returns a value. setInterval()返回一个值。 I've read several examples. 我读了几个例子。 I have not been successful. 我没有成功。

Test page: http://flamencopeko.net/icons_cogo_16.php 测试页: http : //flamencopeko.net/icons_cogo_16.php

JSON thing: http://flamencopeko.net/icons_ajax.php JSON内容: http//flamencopeko.net/icons_ajax.php

Source: http://flamencopeko.net/icons_cogo_16.txt 资料来源: http : //flamencopeko.net/icons_cogo_16.txt

Source: http://flamencopeko.net/icons_ajax.txt 资料来源: http : //flamencopeko.net/icons_ajax.txt

You need to assign the setInterval function to a variable 您需要将setInterval函数分配给变量

var interval = setInterval(function () {});

clearInterval(interval)

I am assuming that is what you are after. 我假设那是你所追求的。

You have to name your interval first to be able to clear it. 您必须先命名间隔才能清除。 Here's what I would do to your code: 这是我要对您的代码执行的操作:

    var newInterval;
    // Event listeners
    $("#play").click(function() { 
        fetchImage(next); 
        newInterval = setInterval(function() { 
            fetchImage(next); 
        }, 1000); 
        return false;
    });

    $("#stop").click(function() { 
        clearInterval(newInterval); 
        return false;
    });

you gave the answer yourself 你自己给答案

"it returns a value" “它返回一个值”

so let it return an alias for a value, a so called variable, ideally you declare it before so it doesnt throw undefined exception when you try to clear it an no #play was clicked befre 因此,让它返回一个值的别名,即所谓的变量,理想情况下,您在声明之前就声明了它,以便在尝试清除它时不会引发未定义的异常,而无需单击#play

var xxx;
... 
$("#play").click(function() { fetchImage(next);xxx=setInterval(function() { fetchImage(next); }, 1000); return false;});
...
clearInterval(xxx)...

Have you ever used one of those "take a number" devices which extrude numbered slips of paper? 您是否曾经使用过其中一种挤出数字纸条的“取号”设备?

The return value from setInterval() is like a "Repeating Task ID#". setInterval()的返回值类似于“重复任务ID#”。

You shouldn't care how big the number is, but you should store it somewhere, and then you can pass it back into clearInterval() to tell the system which task to stop running. 您不必在乎数字有多大,而应该将其存储在某个地方,然后可以将其传递回clearInterval()以告知系统停止运行哪个任务。

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

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