每次布尔值在JavaScript中变为false时调用函数

时间:2015-01-07 11:44:38

标签: javascript html function boolean

每次html音频元素的“暂停”属性变为假时,我都会尝试调用函数。
我有一个计时器,它可以计算实际收听音频文件的时间(我也希望在使用时间栏搜索时排除时间)。
我尝试使用SetInterval一直检查状态为“暂停”。不幸的是,这不能正常工作,并且经常错过状态变化,所以让时间计数器依赖 每次布尔值更改时是否有一种简单的方法来调用函数? 非常感谢帮助。

谢谢,f。

谢谢你的回答。不幸的是,这并没有成功。

以下是代码:

<html>
<head>
</head>
<body>
<h5 id="test">Audio Timer</h5>

<audio id="player" src="kerry.wav" controls></audio>
<form name="d">
    <input type="text" size="8" name="d2">
    <h1 id="time"></h1>
</form>

<script>
    var audio = document.getElementById("player");
    var millisec = 0;
    var seconds = 0;
    var timer;

    function display() {
        if (millisec >= 99) {
            millisec = 0
            seconds += 1
        } else
            millisec += 1
        document.d.d2.value = seconds + "." + millisec;
        timer = setTimeout("display()", 10);
    }

    function starttimer() {

        if (timer > 0) {
            return;
        }
        display();
    }

    function stoptimer() {
        clearTimeout(timer);
        timer = 0;
    }

    function startstoptimer() {
        if (timer > 0) {
            clearTimeout(timer);
            timer = 0;
        } else {
            display();
        }
    }

    function resettimer() {
        stoptimer();
        millisec = 0;
        seconds = 0;
    }

    setInterval(function () {
        var time = audio.paused;
        if (time == false) {
            startstoptimer();
        }
    }, 1);
</script>
</body>
</html>

不幸的是SetInterval(function()..不够快,无法跟踪audio.paused。这似乎是我需要的。正如你所看到的,这段代码总是会启动计时器,但通常它不会当您按暂停或使用时间栏搜索音频时停止它。

知道如何实现这个目标吗?

2 个答案:

答案 0 :(得分:0)

创建一个调用音频标签的变量

var yourAudio = document.getElementById("audio")

然后

yourAudio.onpause=YourFunction()

如果这不是您要找的,请发布您的代码或部分代码,提供更多信息。

答案 1 :(得分:0)

有一段时间(真实)我的页面甚至没有加载。
但是我终于通过添加两个监听“play”和“pause”的事件监听器来调用startstoptimer函数。

audio.addEventListener("playing", startstoptimer);
audio.addEventListener("pause", startstoptimer);

这两条线都是需要的:) 感谢。