setInterval函数不停止但无限运行(setInterval function not stopping but runs infinitely)

编程入门 行业动态 更新时间:2024-10-27 19:27:33
setInterval函数不停止但无限运行(setInterval function not stopping but runs infinitely)

请检查这个: http : //jsfiddle.net/wmaokqh3/

<div id="message"> </div> <audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3"> </audio> <div id="count"> </div> function Typer() { var dfd = $.Deferred(); var srcText = 'EXAMPLE'; var i = -(1); var result = ''; setInterval(function() { if (i == srcText.length) { clearInterval(this); dfd.resolve(); }; $("#count").append('<br>i =' + i + ' , '); i++; result += srcText[i].replace("\n", "<br />"); $("#message").html(result + '---' + i + ' , '); }, 1000); return dfd.promise(); } function playBGM() { var playsound = $.Deferred(); $('#bgm')[0].play(); $("#bgm").on("ended", function() { playsound.resolve(); }); return playsound.promise(); } function thirdFunction() { alert('third function'); } Typer().then(playBGM).then(thirdFunction);

Please check this on : http://jsfiddle.net/wmaokqh3/

<div id="message"> </div> <audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3"> </audio> <div id="count"> </div> function Typer() { var dfd = $.Deferred(); var srcText = 'EXAMPLE'; var i = -(1); var result = ''; setInterval(function() { if (i == srcText.length) { clearInterval(this); dfd.resolve(); }; $("#count").append('<br>i =' + i + ' , '); i++; result += srcText[i].replace("\n", "<br />"); $("#message").html(result + '---' + i + ' , '); }, 1000); return dfd.promise(); } function playBGM() { var playsound = $.Deferred(); $('#bgm')[0].play(); $("#bgm").on("ended", function() { playsound.resolve(); }); return playsound.promise(); } function thirdFunction() { alert('third function'); } Typer().then(playBGM).then(thirdFunction);

最满意答案

不知道你在哪里学会了clearInterval(this)但那是不正确的。 this与当前的时间间隔无关。 您需要使用间隔的生成ID来取消它。

var myInterval = window.setInterval( )

在你的代码中你需要使用这个ID

clearInterval(myInterval)

Not sure where you learned to do clearInterval(this) but that is not correct. The this has nothing to do with the current interval. You need to use the generated id for the interval to cancel it.

var myInterval = window.setInterval( )

and in your code you need to use that id

clearInterval(myInterval)

更多推荐

本文发布于:2023-07-22 06:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1217916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   function   setInterval   infinitely   runs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!