0

我希望这发生在一个无限循环中,我可以在某个时候退出,但这不是重点..

所以我有一个带有视频或图像的 dom 元素列表。

我先看看,这是不是图片,如果是的话:

Display the image for X seconds
Then continue

如果是视频

I play the video, and on the onend event, I continue

现在我重新开始这个过程,再看一遍,视频还是图像?所以流程永远持续下去,当它到达终点时,它只是进入第一个元素。

现在做所有这些都不是问题,但是将其放入循环中并暂停 X 时间,或者直到视频播放完毕,我被卡住了。

这就是它的样子:

func = () ->
console.log "Loop started, now wait X seconds"

delay 3000, ->
    console.log "OK, I waited 3 seconds, now lets go on"

delay 1000, ->
    console.log "Cool, I waited another second, now lets go on"
console.log "Ok, nothing to do, lets start again.."
func()

因此,在这种情况下,此循环应每 4 秒重新启动一次我可以查看的方法有什么想法吗?

4

2 回答 2

1

我认为你的代码应该是这样的结构:

status = 'nothing'

function loop() {
    if status == 'nothing'

        if next item is image
            show image
            status = 'image'
            countdown = 1000 // time to display the image

        if next item is video
            play video
            videoIsEnded = false
            status = 'video'
            video.onend = function { videoIsEnded = true }

    if status == 'image'
        if countdown-- < 0
            hide image
            status = 'nothing'

    if status == 'video'
        if videoIsEnded
            hide video
            status = 'nothing'
}

setInterval(loop, 1000) // check the status every second
于 2013-02-07T10:26:22.073 回答
0

不要使用无限循环。

请改用requestAnimationFrame

    // shim layer with setTimeout fallback
    window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function( callback ){
                window.setTimeout(callback, 1000 / 60);
              };
    })();


    // usage: 
    // instead of setInterval(render, 16) ....

    (function animloop(){
      requestAnimFrame(animloop);
      render();
    })();
    // place the rAF *before* the render() to assure as close to 
    // 60fps with the setTimeout fallback.

为了暂停,您可以使用时间戳:

http://jsfiddle.net/q7qrP/1/

于 2013-02-07T10:26:30.247 回答