Skip to content

Instantly share code, notes, and snippets.

@olegdovger
Last active October 20, 2017 11:11
Show Gist options
  • Save olegdovger/c5d48c1ae4c351b75a5b5c92f9be90c0 to your computer and use it in GitHub Desktop.
Save olegdovger/c5d48c1ae4c351b75a5b5c92f9be90c0 to your computer and use it in GitHub Desktop.
Time Interval
import Ember from 'ember';
import { task, timeout } from 'ember-concurrency';
export default Ember.Controller.extend({
appName: 'Example - Interval',
/////////////////// - task - setInterval /////////////////////
timeTask: new Date().getTime(),
tickTask: task(function * () {
this.set('timeTask', new Date().getTime());
yield timeout(1000);
this.get('tickTask').perform();
}).keepLatest(),
//////////////////////////////////////////////////
/////////////////// - Ember.run - setInterval /////////////////////
ms: 1000,
time: new Date().getTime(),
timer: null,
tick() {
let ms = this.get('ms');
if (new Date().getTime() - this.get('time') >= ms) {
this.set('timer', Ember.run.later(this, 'tick', ms));
this.set('time', new Date().getTime());
}
},
tickStop() {
Ember.run.cancel(this.get('timer'));
},
//////////////////////////////////////////////////
/////////////////////// ajax /////////////////////
ajaxTask: task(function * (text) {
if (!text) {
this.set('ajaxResults', []);
return;
}
yield timeout(250);
let xhr;
try {
xhr = $.getJSON(`https://maps.googleapis.com/maps/api/geocode/json?address=${text}&sensor=false`).then((json) => {
let { results } = json;
this.set('ajaxResults', results);
});
yield xhr;
} finally {
xhr.abort();
}
}).restartable()
//////////////////////////////////////////////////
});
<h1>{{appName}}</h1>
<br>
<br>
{{outlet}}
<br>
<br>
<div>{{timeTask}}</div>
<br>
<button {{action (perform tickTask)}}>start</button>
<button {{action (cancel-all tickTask)}}>stop</button>
<br>
<hr>
<br>
<div>{{time}}</div>
<br>
<button {{action tick}}>start</button>
<button {{action tickStop}}>stop</button>
<br>
<hr>
<br>
{{input value=text action=(perform ajaxTask text) on="input"}}
<br>
{{#unless ajaxTask.isIdle}}
Loading...
{{/unless}}
<ol>
{{#each ajaxResults as |item|}}
<li>{{item.formatted_address}}</li>
{{/each}}
</ol>
{
"version": "0.12.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "2.12.1",
"ember-concurrency": "0.8.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment