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)更多推荐
发布评论