一段时间后运行Javascript函数

时间:2014-11-18 19:47:23

标签: javascript jquery html

我是编程和javascript的新手。

我想做什么: 在pageload上运行的Javascript函数,在本例中为showVideo()。我希望运行此功能10秒,然后转到下一个功能。

function(){
     dostuff();
  // dostuff for 10 seconds
  // now stop dostuff
  // donewstuff();
}  

    <div class="wrapper">
        <div class="screen" id="screen-1" data-video="vid/river.mp4">
            <img src="img/bird.jpg" class="big-image" />
        </div>
        <div class="screen" id="screen-2" data-video="vid/sim.mp4">
            <img src="img/spider.jpg" class="big-image" />
        </div>
    </div>
        </div>

<script>
        $(function(){
            var 
                BV,
                videoPlayer,
                BV = new $.BigVideo();
                BV.init();
                showVideo();
                BV.getPlayer();



            function showVideo() {
                BV.show($('#screen-1').attr('data-video'),{ambient:true});
                $('#screen-1').find('.big-image').transit({'opacity':0},500)
                setTimeout(function(){showVideo2},40000);
            }
            function showVideo2() {
                BV.show($('#screen-2').attr('data-video'),{ambient:true});
                $('#screen-2').find('.big-image').transit({'opacity':0},500)
            }

我试过了:

setTimeout(function(){showVideo2},40000) 

但它不起作用。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

你实际上没有调用该函数。试试这个:

setTimeout(function() {
    showVideo2();
}, 40000);

请注意()中的showVideo2()

答案 1 :(得分:0)

您可以使用setTimeout()

var stopped = false;
setTimeout(function() {
  stopped = true;
}, 10000);

while (!stopped) {
  // Do stuff here.
}

答案 2 :(得分:0)

我的猜测是你要调用showVideo,然后40s后调用showVideo2。你所拥有的是关闭的,但你没有在超时时调用showVideo2。

你有两个解决方案可以修复它:

更改

        function showVideo() {
            BV.show($('#screen-1').attr('data-video'),{ambient:true});
            $('#screen-1').find('.big-image').transit({'opacity':0},500)
            setTimeout(function(){showVideo2},40000);
        }

要么:

        function showVideo() {
            BV.show($('#screen-1').attr('data-video'),{ambient:true});
            $('#screen-1').find('.big-image').transit({'opacity':0},500)
            setTimeout(showVideo2,40000);
        }

或:

        function showVideo() {
            BV.show($('#screen-1').attr('data-video'),{ambient:true});
            $('#screen-1').find('.big-image').transit({'opacity':0},500)
            setTimeout(function(){showVideo2(); },40000);
        }

没有测试,这应该工作。如果您有任何问题,请发表评论。