在特定时间段内为值设置动画

时间:2019-06-08 21:22:42

标签: javascript

我认为在a秒内创建一个将bx的值动画化的函数并不难,但是我想我错了,或者我只是累了,无论如何我用javascript完成。

该函数应类似于此:

const varToChange = 0;
const amount = 100;
const time = 2; // time is in seconds but milisecons are also ok, doesn't really matter.
// feel free to add more parameters if necessary.
changeValueOverTime(amount, time) {
  // magic
}

预期结果varToChange应该是2秒后的100

3 个答案:

答案 0 :(得分:0)

首先,如果您希望对varToChange进行突变,则不应将其const声明为setTimeout。其次,使用let varToChange = 0; const amount = 100; const time = 2; function changeValueOverTime(amount, time) { setTimeout(() => { varToChange = amount; }, time * 1000); } changeValueOverTime(amount, time); setTimeout(() => { console.log(varToChange); }, 3000);

setTimeout

第二个varToChange在那里,因此您可以看到std::vector<std::unique_ptr<Agent>>;

的更新值。

答案 1 :(得分:0)

您可以使用setInterval个javascript方法中的setTimeout个来做到这一点。

let varToChange = 0;
const amount = 100;
const time = 2;
    
function changeValueOverTime(amount, time) {
  setTimeout(function(){
  varToChange++;
  console.log("varToChange : "+varToChange);
  varToChange !== amount ? changeValueOverTime(amount,time) : console.log("done");
  },(time*1000)/amount)
}

changeValueOverTime(amount,time);

答案 2 :(得分:-1)

这是我在playcode中创建的函数,也许我应该已经澄清该函数应该是准确的,该函数总是在给定时间后返回准确的金额。

var shopifyAjaxAddURL = '/cart/add.js';
var shopifyAjaxCartURL = '/cart.js';
var shopifyAjaxStorePageURL = '/search';

$(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function (e) {
    var $form = $(this);

    //Add to cart
    $.post(shopifyAjaxAddURL, $form.serialize(), function (itemData) {
        if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }
        else {
            //Enable add button
        $btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
        setTimeout(function () {

            //Not added, show message
            if (typeof (data) != 'undefined' && typeof (data.status) != 'undefined') {
                var jsonRes = $.parseJSON(data.responseText);
                window.showQuickPopup(jsonRes.description, $btn);
            } else {
                //Some unknown error? Disable ajax and submit the old-fashioned way.
                $form.addClass('noAJAX');
                $form.submit();
            }
        }  
    });