简体   繁体   中英

How to make an onscreen counter that blocks the function till a counter is done

On my website I want to display an onscreen event once a button is clicked to record a wbcam (so that people know when the recording starts).

I want to use a jQuery/JavaScript method that once called, blocks the function that is running and displays "3, 2, 1" (counting down) in screen. After that I want the function to continue.

I found the JQuery AnimateCount function and a jquery-count-to plugin but I cannot get it to work.

Can someone help me out?

/edit non-working code:

I have a function that starts the recording of the webcam as follows:

function startRecording() {
    $("#recordStartButton").attr("disabled", true);
    $("#recordStopButton").attr("disabled", false);
    $("#recordPauseResumeButton").attr("disabled", false);
    $.scriptcam.startRecording();
}

I call this function once a user clicks "Start Recording" with a function that has a callback as follows:

<button id="recordStartButton" class="success" onclick="startRecordingWithCounter(startRecording)" disabled>Start Recording</button>&nbsp;

where startRecordingWithCounter(startRecording) looks like this:

function startRecordingWithCounter(callback) {
    $('#message').animateCount(1, 3);
    callback();
}

this only displays "3" in the message div and then just starts recording...

This code:

$('#message').animateCount(1, 3);
callback();

Tells the plugin to start a count animation. But that call does not "block" until the animation is complete - it returns from the function immediately. (This is important since Javascript is a single-threaded language. Locking functions would cause ugly browser freezes.)

So the animateCount function returns immediately, and callback is called immediately!

However the library you are using does allow you to specify an onComplete function. So you should do it that way:

$('.message').countTo({
    from: 1,
    to: 3,
    speed: 3000,
    refreshInterval: 50,
    formatter: function (value, options) {
        return value.toFixed(options.decimals);
    },
    onComplete: callback
});

The library should call your callback function when the animation has finished.

I don't know if you need to provide the formatter function or not.


An alternative would be to simply change your current code from:

callback();

to:

setTimeout(callback, 3000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM