logo
down
shadow

Underscorejs 'defer' (or setTimeout 1) not working consistently


Underscorejs 'defer' (or setTimeout 1) not working consistently

By : Kerwin Chen
Date : November 16 2020, 06:23 AM
it should still fix some issue I found a solution to my problem. Although it is expected that _.defer (of setTimeout 1) should have worked... it wasn't very consistent in my case. So I ended up using the requestAnimationFrame method. Heres the updated version:
code :
var expensiveOperation = function () {
    for (var i = 0; i < 10000; i++) {
        for (var j = 0; j < 4500; j++) {
            Math.random();
        }
    }
};


var $box1 = $('#box-1');


$('#show-1').click(function () {
    $box1.show();
    expensiveOperation();
});

$('#showDefer').click(function () {
    $box1.show();
    _.defer(expensiveOperation);
});

$('#hide-1').click(function () {
    $box1.hide();
    expensiveOperation();
});

$('#hideDefer').click(function () {
    $box1.hide();
    _.defer(expensiveOperation);
});

var $box2 = $('#box-2');

$('#show-2').click(function () {
    $box2.show();
    expensiveOperation();
});

$('#showRequestAnimationFrame').click(function () {
    var flag = true;
    requestAnimationFrame(function showAnimFrame(){
        if(flag) {
            $box2.show();
            flag = false;
            requestAnimationFrame(showAnimFrame);
        } else expensiveOperation();
    });
});

$('#hide-2').click(function () {
    $box2.hide();
    expensiveOperation();
});

$('#hideRequestAnimationFrame').click(function () {
     var flag = true;
    requestAnimationFrame(function showAnimFrame(){
        if(flag) {
            $box2.hide();
            flag = false;
            requestAnimationFrame(showAnimFrame);
        } else expensiveOperation();
    });
});
#box-1 {
    background-color:red;
    width:100px;
    height:100px;
}

#box-2 {
    background-color:blue;
    width:100px;
    height:100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="box-1"></div>
<button id="show-1">show</button>
<button id="showDefer">show defer</button>
<button id="hide-1">hide</button>
<button id="hideDefer">hide defer</button>

<p></p>

<div id="box-2"></div>
<button id="show-2">show</button>
<button id="showRequestAnimationFrame">show requestAnimationFrame</button>
<button id="hide-2">hide</button>
<button id="hideRequestAnimationFrame">hide requestAnimationFrame</button>


Share : facebook icon twitter icon
Defering javascript - what is the correct html syntax defer or defer="defer"

Defering javascript - what is the correct html syntax defer or defer="defer"


By : RandomMan
Date : March 29 2020, 07:55 AM
should help you out defer is a boolean attribute [HTML 4.01 spec]:
code :
<OPTION selected>
<OPTION selected="selected">
Why cannot access array's value when using Ext.Function.defer (setTimeout)?

Why cannot access array's value when using Ext.Function.defer (setTimeout)?


By : Sergy.p
Date : March 29 2020, 07:55 AM
hope this fix your issue That's because defer will run asynchronously, you are accessing arr in a state where it is not populated with the data you want to
Edit: You can test this code to understand defer
code :
Ext.Function.defer(function() {
    console.log("You will see this message later although it is written first");
}, 1000);
console.log("You will see this message first although it is written after");
Ext.Function.defer(function() {
    var arr = [];
    Ext.Array.forEach(panel.query('grid'), function(grid) {
        arr.push(grid.collapseTool.getId());
    });
    onDone(arr);
}, 1000);

function onDone(arr) {
    console.log(arr);
}
JavaScript: setTimeOut inside another setTimeOut (nested setTimeOut) to stimulate the API response not working

JavaScript: setTimeOut inside another setTimeOut (nested setTimeOut) to stimulate the API response not working


By : Waltton Santana
Date : March 29 2020, 07:55 AM
Does that help you need to pass as a argument the current index, so then you need to multiply that index for your current api call delay, so when is the first step it will be (index = 0), so you should do it something like (index + 1) * apiDelay then it would be 5000, sencond step, index would be 1 then (index + 1) * apiDelay would be 10000, and the last step index would be 2, then (index + 1) * apiDelay would be 15000.
At the bottom some modification was done to your current code.
code :
var dataset = [10, 20, 30];
var delay = 100;
var apiDelay = 5000;



function execute(dataset) {    
    var i = 0;
    scannedJob(dataset, i);
}


//1ST TIME OUT METHOD//
function scannedJob(dataset, i) {

    setTimeout(function() {
              console.log("Scanned Job Number ="+dataset[i]+" @  time = " + new Date().toLocaleTimeString());


        fireJobSearchHttpAPI1(dataset[i], i);

        i++;

        if (dataset.length > i) {
            self.scannedJob(dataset, i);
        } else {
            i = 0;
        }
    }, delay);
}

//2nd TIME OUT METHOD//

/* TWO TYPES OF METHODS I WRITTEN , BOTH ARE NOT WORKING,
EXPECTED:  Each API call should fire with 5sec delay. Instead all 3 api calls given response after 5 seconds. I need each call should take 5sec and total at the end it should take 15 seconds., 
BUT FIRING ALL THE JOB NUMBERS IMMEDIATELY WITHOUT DELAY
*/
function fireJobSearchHttpAPI1(jobNum, index) {
        console.log("index", ((index + 1) * apiDelay))
        setTimeout(function() {
            console.log("job number '"+jobNum+"' API FIRED @ " + new Date().toLocaleTimeString());
        }, ((index + 1) * apiDelay));

}


function fireJobSearchHttpAPI2(jobNum) {
    (function myLoop(i) {
        setTimeout(function() {
            console.log("job number '"+jobNum+"' API FIRED  @ " + new Date().toLocaleTimeString());
           if (--i) myLoop(i);
        }, apiDelay)
    })(1);

}


//Main Method
execute(dataset);
underscorejs each function is not working

underscorejs each function is not working


By : Syed Mostofa Monsur
Date : March 29 2020, 07:55 AM
around this issue I think the problem with the CDN. If you want language then you need to assign val.Language.And also array definition wrong.Give new Array or [] instead of {}.Try the below one:
underscorejs where operator not working as expected

underscorejs where operator not working as expected


By : spartdark
Date : March 29 2020, 07:55 AM
it should still fix some issue this is the json content of album.tracks.items
code :
var data = [ { disc_number: 1,
     duration_ms: 286013,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/0cahtHEywK64NSWqm2SDTi' },
     href: 'https://api.spotify.com/v1/tracks/0cahtHEywK64NSWqm2SDTi',
     id: '0cahtHEywK64NSWqm2SDTi',
     is_local: false,
     name: 'Help I\'m Alive',
     preview_url: null,
     track_number: 1,
     type: 'track',
     uri: 'spotify:track:0cahtHEywK64NSWqm2SDTi'},
   { disc_number: 1,
     duration_ms: 257413,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/2uxLjFYEoQ7xsqfMPuwTQ9' },
     href: 'https://api.spotify.com/v1/tracks/2uxLjFYEoQ7xsqfMPuwTQ9',
     id: '2uxLjFYEoQ7xsqfMPuwTQ9',
     is_local: false,
     name: 'Sick Muse',
     preview_url: null,
     track_number: 2,
     type: 'track',
     uri: 'spotify:track:2uxLjFYEoQ7xsqfMPuwTQ9'}, 
   { disc_number: 1,
     duration_ms: 222933,
     explicit: true,
     external_urls:
      { spotify: 'https://open.spotify.com/track/5lVXRLV1LgQgd7kUGt3Mae' },
     href: 'https://api.spotify.com/v1/tracks/5lVXRLV1LgQgd7kUGt3Mae',
     id: '5lVXRLV1LgQgd7kUGt3Mae',
     is_local: false,
     name: 'Satellite Mind',
     preview_url: null,
     track_number: 3,
     type: 'track',
     uri: 'spotify:track:5lVXRLV1LgQgd7kUGt3Mae'},
   { disc_number: 1,
     duration_ms: 293600,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/616NBqU3gbjICFB1npf2vg' },
     href: 'https://api.spotify.com/v1/tracks/616NBqU3gbjICFB1npf2vg',
     id: '616NBqU3gbjICFB1npf2vg',
     is_local: false,
     name: 'Twilight Galaxy',
     preview_url: null,
     track_number: 4,
     type: 'track',
     uri: 'spotify:track:616NBqU3gbjICFB1npf2vg'},
   { disc_number: 1,
     duration_ms: 245280,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/6JhUq57XpJeNMxboI4Ne3S' },
     href: 'https://api.spotify.com/v1/tracks/6JhUq57XpJeNMxboI4Ne3S',
     id: '6JhUq57XpJeNMxboI4Ne3S',
     is_local: false,
     name: 'Gold Guns Girls',
     preview_url: null,
     track_number: 5,
     type: 'track',
     uri: 'spotify:track:6JhUq57XpJeNMxboI4Ne3S'},
   { disc_number: 1,
     duration_ms: 234586,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/4z2xy1UYMu70xCkWudeL96' },
     href: 'https://api.spotify.com/v1/tracks/4z2xy1UYMu70xCkWudeL96',
     id: '4z2xy1UYMu70xCkWudeL96',
     is_local: false,
     name: 'Gimme Sympathy',
     preview_url: null,
     track_number: 6,
     type: 'track',
     uri: 'spotify:track:4z2xy1UYMu70xCkWudeL96'}, 
   { disc_number: 1,
     duration_ms: 286320,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/5dmGvCOyJi943jZgiMdmDC' },
     href: 'https://api.spotify.com/v1/tracks/5dmGvCOyJi943jZgiMdmDC',
     id: '5dmGvCOyJi943jZgiMdmDC',
     is_local: false,
     name: 'Collect Call',
     preview_url: null,
     track_number: 7,
     type: 'track',
     uri: 'spotify:track:5dmGvCOyJi943jZgiMdmDC'},
   { disc_number: 1,
     duration_ms: 214440,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/3Ecg2M5kzSEzz6tR3fOg6g' },
     href: 'https://api.spotify.com/v1/tracks/3Ecg2M5kzSEzz6tR3fOg6g',
     id: '3Ecg2M5kzSEzz6tR3fOg6g',
     is_local: false,
     name: 'Front Row',
     preview_url: null,
     track_number: 8,
     type: 'track',
     uri: 'spotify:track:3Ecg2M5kzSEzz6tR3fOg6g'},
   { disc_number: 1,
     duration_ms: 266840,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/7Apb2lh3o9cYUUHziHNuNN' },
     href: 'https://api.spotify.com/v1/tracks/7Apb2lh3o9cYUUHziHNuNN',
     id: '7Apb2lh3o9cYUUHziHNuNN',
     is_local: false,
     name: 'Blindness',
     preview_url: null,
     track_number: 9,
     type: 'track',
     uri: 'spotify:track:7Apb2lh3o9cYUUHziHNuNN'},
   { disc_number: 1,
     duration_ms: 253693,
     explicit: false,
     external_urls:
      { spotify: 'https://open.spotify.com/track/73PtlKAy67oP9EGeK1fZPi' },
     href: 'https://api.spotify.com/v1/tracks/73PtlKAy67oP9EGeK1fZPi',
     id: '73PtlKAy67oP9EGeK1fZPi',
     is_local: false,
     name: 'Stadium Love',
     preview_url: null,
     track_number: 10,
     type: 'track',
     uri: 'spotify:track:73PtlKAy67oP9EGeK1fZPi'} ];


  var track = _.where(data, {disc_number: 1, track_number: 10});
console.log(JSON.stringify(track))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id="content"></div>
Related Posts Related Posts :
  • How to change add and remove active class in JavaScript
  • how to toggle a specific div in javascript
  • How to get all the values from multiple keys of an array of object?
  • jQuery bind() unbind() and on() and off()
  • regular expression to find DD Month YYYY from a string
  • How to upload files from web client (HTML/jQuery form) to your Dropbox folder
  • Backbone history and require.js issue
  • Confusion over Classical and Prototypal Inheritance Javascript
  • How to take screen shot of current webpage using Javascript/JQuery?
  • Store meridiem in a variable
  • class declared inside closure vs standard class without closure
  • javascript confirm box always return true
  • dynamically changing the size of font size based on text length using css and html
  • Node.js - Getting the host IP address while on Amazon EC2
  • Confusing CSS, can anyone explain please
  • How to install v8-profiler on Windows 8 (64 bit) using npm?
  • Resolve promise based on another promise
  • google maps adding overlay layer above UI and markers
  • Style specific letter?
  • RangeError: Maximum call stack size exceeded with array.slice
  • node rest client get with local variable
  • If condition not executes while mouse move fastly
  • Count the number of displayed elements in a HTML list
  • Locate JavaScript source code in Emacs
  • Clean, Modular Code vs MV* Frameworks
  • infinite scroll without loading image
  • Backbone: reverse collection order with comparator
  • What do printers ignore?
  • jQuery UI .tabs() Contentless tab?
  • Execute Javascript alert() after page (visually) loaded
  • JavaScript - duplicating array doesn't work
  • Excessive clickable area below image
  • JavaScript Regex: Replace |b| with <b>
  • Unexpected value change in 2D array in JavaScript
  • Function doesnt see parameter as a array of objects
  • jQuery fetch keypress event on chrome and IE
  • How to enable jquery validate localization?
  • Cassandra map collection returned by node.js Helenus looks odd
  • angular ng-repeat with multiple filter options
  • Selecting Children without ID or Class names
  • How to uncheck a group of checkboxes when another checkbox is checked
  • Is hiding content by Javascript or jQuery Worth trying
  • Load XUL resource using javascript
  • XML to HTML text area from server file system
  • set focus() on textbox on form onload
  • es lint '' is assigned a value but never used' eventhough i have used it
  • Can "name" attribute be used for custom VueJS components
  • Get innerHTML of content when it is clicked
  • HTTPS causes CSS animations to not load? Very confused
  • How to hide other div apart from touched div to the band
  • Is global variable assignment atomic on NodeJS?
  • Datepicker onchangemonthyear beforeshowday
  • trying to render html files using jade but it still adresses it as a jade
  • Google Analytics - Understanding and Dissecting the Snippet: What is | | [ ];
  • Replacing "[aA09.b]." to "[aA09.b]\n" in in JavaScript
  • Why wrap a function definition in an immediate function?
  • Enable / disable jQuery script on switching to different tab in a HTML page
  • how can find return variable value outside anonymous function in node js mysql query function
  • Converting 1 to 0001 in javascript array
  • svg viewbox should not resize the text fontSize?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org